user389955
user389955

Reputation: 10467

How to keep a docker container run for ever

I created a Dockerfile which sets up python environment so that when people run the image in their host, they can run my python file without installing multiple python packages themselves.

The problem is after I build and run the image, the container stopped immediately (because it completed).

How can I keep the container running forever? My understanding is after people pull and run my image, they can start to run python file by running "python file.python".

my Dockerfile looks like this (may not be correct. I am still learning):

FROM python:3-alpine
ADD . /app
WORKDIR /app
RUN pip install configparser

Upvotes: 8

Views: 14659

Answers (3)

Mies van der Lippe
Mies van der Lippe

Reputation: 672

Your Dockerfile is lacking a CMD. It doesn't do anything right now.

You need to append the following;

## Run the script
CMD [ "python", "-u", "./your-script.py"]

I'm adding -u so Python runs in unbuffered output mode. If you don't, you probably won't see output from your script.

If you now start your container attached, you can view it's output

docker run your-container

You can also run it detached, and attach later.

docker run -d --name container-name your-container

Naming your container makes it significantly easier to manage it's lifetime.

Attach to your output using either

docker logs container-name 

Or with interaction using

docker attach container-name

Upvotes: 4

Lebecca
Lebecca

Reputation: 2878

From HOW TO KEEP DOCKER CONTAINERS RUNNING, we can know that docker containers, when run in detached mode (the most common -d option), are designed to shut down immediately after the initial entrypoint command (program that should be run when container is built from image) is no longer running in the foreground. So to keep docker container run even the inside program has done

  • just add CMD tail -f /dev/null as last line to dockerfile

What's more important is that we should understand what's docker is intended for and how to use it properly. Try to use docker as environment foundation for applications in host machine is not a good choice, docker is designed to run applications environment-independent. Applications should be placed into docker image via docker build and run in docker container in runtime.

Upvotes: 13

Dean Christian Armada
Dean Christian Armada

Reputation: 7384

Depends on how you run your image.. You can do command below so it is interactive and you can execute more commands inside the contaner after it has run

docker run -it <your-image> bash

Upvotes: 4

Related Questions