🧟‍♂️ How to keep a Docker container aliveMay 20, 2021Docker 351 words

Docker is a great tool. It helps you build software with consistent environment across all platforms, so that you don’t have to worry about ‘It works on my machine’ issues. Simply put, Docker provides capabilites to create an Operating System without a User Interface. You can do everything that you normally do on an OS, like running servers, installing packages, even browse the internet, but using just the command prompt. In Docker terms, it’s called an image.

Running an instance of a Docker image, is known as a container. You can run multiple container of the same image.

Note: Before you continue, make sure you install docker using the recommended steps for your operating system.

A basic Dockerfile would look something like this:

FROM node:10-alpine
WORKDIR /home/node/app
COPY ./my-app ./
USER node
RUN npm install
COPY --chown=node:node . .
CMD [ "node", "app.js" ]

Here we are copying our Node app into the image and running it using node app.js. Now what happens when your container fails to start? The app works as expected on your local machine, but only fails when running with Docker. In such cases, we can usually get a log file to figure out what went wrong.

docker logs --tail=50 <container id>

I’ve faced scenarios where there were no logs, so the above command was as useless as Red Lights in Grand Theft Auto. In such cases I need to enter the container using docker exec command and debug whats wrong. But to do that, the container should be running.

Here are a couple of ways you can keep the container running to inspect what’s going on in the container.

If you are using a Dockerfile, any one of these options should do the trick.

ENTRYPOINT ["tail", "-f", "/dev/null"]
CMD ["tail", "-f", "/dev/null"]
CMD ["sleep", "infinity"]

If you are using a docker-compose.yml file,

version: '3'
    image: node:8
    tty: true

Note: If you use Dockerfile for image and CMD in Dockerfile, this option won’t work; however, you can use the entrypoint option in the compose file which clears the CMD from the Dockerfile.

Another option is to use command option and specify the same commands which we used in Dockerfile above.

version: '3'
    image: ubuntu
    command: tail -F /dev/null

Now the containers are always running, you can use docker exec to enter the container and debig your code.

Obviously this is for development purposes only, you shouldn’t need to keep a container alive unless it’s running a process. If you decide to use this in production, drop a comment below, I’m curious to understand your use-case.