Millet Porridge

English version of https://corvo.myseu.cn

0%

Docker Series 3: Startup

ENTRYPOINT vs CMD

There are many blogs about the ENTRYPOINT and CMD, I have refered to offical blog and docker-run-vs-cmd-vs-entrypoint.

1
An ENTRYPOINT allows you to configure a container that will run as an executable.
1
Command line arguments to docker run <image> will be appended after all elements in an exec form ENTRYPOINT, and will override all elements specified using CMD.

I’ll give you some examples:

only ENTRYPOINT

1
2
3
4
FROM debian:buster-slim
RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list
RUN apt-get update && apt-get install -y htop
ENTRYPOINT ["htop"]
1
2
3
4
docker run -ti test

# It's the `htop -C` to be executed.
docker run -ti test -C

CMD with ENTRYPOINT

1
2
3
4
5
FROM debian:buster-slim
RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list
RUN apt-get update && apt-get install -y htop
ENTRYPOINT ["htop"]
CMD ["-C"]

It’s just like you are executing the htop -C.

1
docker run -ti test

replace ENTRYPOINT

What if we don’t want to execute htop, we want to get a bash to execute some commands. The answer is --entrypoint. Noted that it should be written in front of the image name, otherwise it will be treated as a CMD

1
docker run -ti --entrypoint=/bin/bash <image>

There are sereval senearios we need it:

  1. We want to check the entrypoint and cmd after we create the Dockerfile
  2. Some times, the container couldn’t run for some reasons, we need to hack the image and try to run entrypoint command by ourselves, it’s faster then reading logs.

Write your own ENTRYPOINT script

The entrypoint can be a simple script, especially if you want to perform some checks before your program runs.

This script could help you make sure that the log directory is mounted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/bash

set -e

DATA_DIR=/home/data

# Make sure the dir has been mounted.
[ -d "$DATA_DIR" ] || exit 1

# make sure the dir will create.
mkdir -pv $DATA_DIR/{log,run,scripts}
chown -R corvo:corvo $DATA_DIR

exec "$@"

The exec "$@" just run the CMD, this is an example Dockerfile.

1
2
3
4
5
6
FROM debian:buster-slim
RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list
RUN apt-get update && apt-get install -y htop
COPY entryproint.sh entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
CMD ["uwsgi", "-y", "app.yaml"]