How to run command on container startup, and keep container running after command is done?

Viewed 321

I have a Dockerfile, which is meant to use script1, like so:

# Pull from Debian
FROM debian
    
# Update apt and install dependencies
RUN apt update
RUN apt -y upgrade
RUN apt -y install wget curl
    
# Download script1.sh
RUN wget -O ./script1.sh https://example.com
    
# Make script1.sh executable
RUN chmod +x ./script1.sh

Currently, I can:

  1. Build this Dockerfile into an image
  2. Run said image in a container
  3. Open a CLI in said container, and run script1 manually (with bash ./script1.sh)
  4. The script runs, and the container stays open.

However, I'd like to automatically run this script on container startup.

So I tried to change my Dockerfile to this:

# Pull from Debian
FROM debian

# Update apt and install dependencies
RUN apt update
RUN apt -y upgrade
RUN apt -y install wget curl

# Download script1.sh
RUN wget -O ./script1.sh https://example.com

# Make script1.sh executable
RUN chmod +x ./script1.sh

# Run script1.sh on startup
CMD bash ./script1.sh

However, when I do this, the container only stays open for a little bit, and then exits right away.

I suspect it exits as soon as script1 is done...

I also tried ENTRYPOINT, without much success.

Why does my container stay open if I open a CLI and run the script manually, but doesn't stay open if I try to automatically run it at startup?

And how can I run the script automatically on container startup, and keep the container from exiting right away?

1 Answers

An old Docker (v2) tricks to prevent premature container closing consisted in letting run an "infinite" loop command in it, such as:

CMD tail -f /dev/null
Related