Docker container exits when using -it option

2019-08-08 20:34发布

Consider the following Dockerfile:

FROM ubuntu:16.04

RUN apt-get update && \
    apt-get install -y apache2 && \
    apt-get clean

ENTRYPOINT ["apache2ctl", "-D", "FOREGROUND"]

When running the container with the command docker run -p 8080:80 <image-id>, then the container starts and remains running, allowing the default Apache web page to be accessed on https://localhost:8080 from the host as expected. With this run command however, I am not able to quit the container using Ctrl+C, also as expected, since the container was not launched with the -it option. Now, if the -it option is added to the run command, then the container exits immediately after startup. Why is that? Is there an elegant way to have apache run in the foreground while exiting on Ctrl+C?

3条回答
孤傲高冷的网名
2楼-- · 2019-08-08 20:52

As yamenk mentioned, daemonizing works because you send it to the background and decouple the window resizing.

Since the follow-up post mentioned that running in the foreground may have been desirable, there is a good way to simulate that experience after daemonizing:

docker logs -f container-name

This will drop the usual stdout like "GET / HTTP..." connection messages back onto the console so you can watch them flow.

Now you can resize the window and stuff and still see your troubleshooting info.

查看更多
何必那么认真
3楼-- · 2019-08-08 20:59

This behaviour is caused by Apache and it is not an issue with Docker. Apache is designed to shut down gracefully when it receives the SIGWINCH signal. When running the container interactively, the SIGWINCH signal is passed from the host to the container, effectively signalling Apache to shut down gracefully. On some hosts the container may exit immediately after it is started. On other hosts the container may stay running until the terminal window is resized.

It is possible to confirm that this is the source of the issue after the container exits by reviewing the Apache log file as follows:

# Run container interactively:
docker run -it <image-id>

# Get the ID of the container after it exits:
docker ps -a

# Copy the Apache log file from the container to the host:
docker cp <container-id>:/var/log/apache2/error.log .

# Use any text editor to review the log file:
vim error.log

# The last line in the log file should contain the following:
AH00492: caught SIGWINCH, shutting down gracefully

Sources:

查看更多
▲ chillily
4楼-- · 2019-08-08 21:09

All that you need to do is pass the -d option to the run command:

docker run -d -p 8080:80 my-container
查看更多
登录 后发表回答