Common Docker commands and Dockerfile

Link to this article: https://xiets.blog.csdn.net/article/details/122866186

Related articles: Docker installation and command index -- help

1. Image management: docker image

docker image Help information:

$ docker image       

Usage:  docker image COMMAND

Manage images

Commands:
  build       Build an image from a Dockerfile
  history     Show the history of an image
  import      Import the contents from a tarball to create a filesystem image
  inspect     Display detailed information on one or more images
  load        Load an image from a tar archive or STDIN
  ls          List images
  prune       Remove unused images
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rm          Remove one or more images
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE

Run 'docker image COMMAND --help' for more information on a command.

1.1 pull image: docker image pull

Can be abbreviated as docker pull , pull the image or warehouse from the registration server:

$ docker image pull --help

Usage:  docker [image] pull [OPTIONS] NAME[:TAG|@DIGEST]

Pull an image or a repository from a registry

Options:
  -a, --all-tags                Download all tagged images in the repository
        --disable-content-trust Skip image verification (default true)
        --platform string       Set platform if server is multi-platform
                                capable
  -q, --quiet                   Suppress verbose output

Pull the ubuntu image. By default, pull the latest tag:

$ docker image pull ubuntu
# or
$ docker pull ubuntu

# Pull the specified label version
$ docker pull ubuntu:tag_name

Pull docker / getting started:

$ docker pull docker/getting-started

# Run a container directly. If there is no corresponding image locally, it will also be pulled automatically
$ docker run -d -p 80:80 docker/getting-started

If you are pulling up a private warehouse, you need to log in and run it first docker login , enter the user name and password. If you have logged in, the information of successful login will be printed.

Need to log out and run docker logout.

1.2 push image: docker image push

Can be abbreviated as docker push , push the image or warehouse to the registration server. You need to log in before pushing.

$ docker image push --help

Usage:  docker image push [OPTIONS] NAME[:TAG]

Push an image or a repository to a registry

Options:
  -a, --all-tags                Push all tagged images in the repository
      --disable-content-trust   Skip image signing (default true)
  -q, --quiet                   Suppress verbose output
  
# Command example
$ docker image push image_name:tag
$ docker image push -a image_name

The pushed image needs to create a corresponding warehouse in the registration server. Create a warehouse:

  1. open https://hub.docker.com/repositories
  2. Click Create Repository and enter the warehouse name, such as docker_username/image_name, including docker_username is the user name of the registration server (fixed warehouse name prefix). You only need to enter image_name.
  3. Select public or private and click Create to Create the warehouse.

Example of push warehouse:

# A label needs to be marked before pushing. In order to make the name of the image warehouse consistent with the name of the warehouse created on the registration server,
# And you can rename the label name, which is equivalent to copying a copy and then creating a new name (the image ID is still unchanged)
$ docker tag local_image:tagname docker_username/image_name:tagname

# Log in to the registration server
$ docker login

# Push the local image warehouse to the registration server
$ docker push docker_username/image_name:tagname

1.3 list images: docker image ls

Can be abbreviated as docker images , list the downloaded images:

$ docker image ls
# or
$ docker images

1.4 delete image: docker image rm

Can be abbreviated as docker rmi , delete one or more mirrors:

$ docker image rm --help

Usage:  docker image rm [OPTIONS] IMAGE [IMAGE...]

Remove one or more images

Aliases:
  rm, rmi, remove

Options:
  -f, --force      Force removal of the image
      --no-prune   Do not delete untagged parents

To delete a ubuntu image:

$ docker image rm ubuntu
# or
$ docker rmi ubuntu

1.6 save image: docker image save

Can be abbreviated as docker save , save one or more images to the tar Archive (you can save multiple images to the same tar archive file):

$ docker image save --help

Usage:  docker image save [OPTIONS] IMAGE [IMAGE...]

Save one or more images to a tar archive (streamed to STDOUT by default)

Options:
  -o, --output string   Write to a file, instead of STDOUT

Save the ubuntu image to the local and save it as ubuntu tar:

$ docker image save -o ubuntu.tar ubuntu
# or
$ docker save ubuntu > ubuntu.tar

1.5 loading image: docker image load

Can be abbreviated as docker load , load the image from the tar archive or SDTIN:

docker image load --help

Usage:  docker image load [OPTIONS]

Load an image from a tar archive or STDIN

Options:
  -i, --input string   Read from tar archive file, instead of STDIN
  -q, --quiet          Suppress the load output

From the local file Ubuntu Tar load image:

$ docker image load -i ubuntu.tar
# or
$ cat ubuntu.tar | docker image load
# or
$ docker image load < ubuntu.tar

1.7 image details: docker image inspect

Can be abbreviated as docker inspect , view the details of the image (image ID, default startup script / command, environment variable, related configuration, etc.):

Usage:  docker image inspect [OPTIONS] IMAGE [IMAGE...]

# Query details of ubuntu image
$ docker image inspect ubuntu

# Query the specified field, query the [{"Id": *}] Field
$ docker image inspect -f "{{.Id}}" ubuntu
sha256:a457a7...

# Query field [{"ContainerConfig": {"Env": *}}]
$ docker image inspect -f "{{.ContainerConfig.Env}}" ubuntu
[PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

# Query field [{"ContainerConfig": {"Cmd": *}}]
$ docker image inspect -f "{{.ContainerConfig.Cmd}}" ubuntu
[/bin/sh -c #(nop)  CMD ["bash"]]

# Query field [{"Architecture": *}]
$ docker image inspect -f "{{.Architecture}}" ubuntu    
arm64

1.8 build image: docker image build

Can be abbreviated as docker build , build an image according to the Dockerfile file. Help information:

$ docker image build --help

Usage:  docker image build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

Options:
      --add-host list           Add a custom host-to-IP mapping (host:ip)
      --build-arg list          Set build-time variables
      --cache-from strings      Images to consider as cache sources
      --disable-content-trust   Skip image verification (default true)
  -f, --file string             Name of the Dockerfile (Default is
                                'PATH/Dockerfile')
      --iidfile string          Write the image ID to the file
      --isolation string        Container isolation technology
      --label list              Set metadata for an image
      --network string          Set the networking mode for the RUN
                                instructions during build (default "default")
      --no-cache                Do not use cache when building the image
  -o, --output stringArray      Output destination (format:
                                type=local,dest=path)
      --platform string         Set platform if server is multi-platform
                                capable
      --progress string         Set type of progress output (auto, plain,
                                tty). Use plain to show container output
                                (default "auto")
      --pull                    Always attempt to pull a newer version of
                                the image
  -q, --quiet                   Suppress the build output and print image
                                ID on success
      --secret stringArray      Secret file to expose to the build (only
                                if BuildKit enabled):
                                id=mysecret,src=/local/secret
      --ssh stringArray         SSH agent socket or keys to expose to the
                                build (only if BuildKit enabled) (format:
                                default|<id>[=<socket>|<key>[,<key>]])
  -t, --tag list                Name and optionally a tag in the
                                'name:tag' format
      --target string           Set the target build stage to build.

Example of building a mirror:

# Dockerfile file content
$ cat Dockerfile 
FROM ubuntu
RUN apt update && apt install -y vim

# Build image
# (warehouse) the image name is mylibrary/ubt and the label is v2 (if not, the default is the latest label)
# . indicates that the local working directory during construction is the current directory, and the Dockerfile file under this directory is used by default
$ docker build -t mylibrary/ubt:v2 .

# After the construction is successful, view the local image
$ docker images

2. Container management: docker container

docker container Help information:

% docker container

Usage:  docker container COMMAND

Manage containers

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container's filesystem
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  inspect     Display detailed information on one or more containers
  kill        Kill one or more running containers
  logs        Fetch the logs of a container
  ls          List containers
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  prune       Remove all stopped containers
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  run         Run a command in a new container
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  wait        Block until one or more containers stop, then print their exit codes

Run 'docker container COMMAND --help' for more information on a command.

2.1 create container: docker container create

Can be abbreviated as docker create , create a new container:

Usage:  docker container create [OPTIONS] IMAGE [COMMAND] [ARG...]

The command usage is basically the same as docker container run. Refer to "running container: docker container run".

2.2 operation container: docker container run

Can be abbreviated as docker run , create and run a new container, which is equivalent to docker create and then docker start CONTAINER. When creating / running a container, if the image is not downloaded, the corresponding image will be downloaded first.

Common parameters:

Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

-d, --detach            # Run the container in the background and print the container ID
-i, --interactive       # Keep STDIN open, even if there is no attachment
-t, --tty               # Assign a terminal, usually used with - t, for example, - it means assign a terminal and keep the standard input open

-e, --env list          # Set environment variable: - VAR1 = Value2, e.g. --
                        # Only the name has no equal sign. For example, -- env USER refers to the local environment variable USER=$USER of the host
--env-file list         # Read environment variables from a file, such as: -- env file/ env_ list. txt
                        # The file content is one environment variable per line (#Behavior comments beginning with the sign will be ignored)
                        # VAR=value means that the value is an environment variable with the name of VAR and the value of value
                        # If USER has only name but no equal sign, it means that the local environment variable USER=$USER of the host is referenced

-p, --publish list      # Publish the port of the container to the host (port mapping: Host - > container), format: - p [ip:]port:port[/type], such as:
                        # -P 80: port 80 of the 8080 host computer is mapped to port 8080 of the container. By default, the IP monitored by the host computer is 0.0.0.0 (that is, all IP addresses). The default type is TCP
                        # -p 127.0.0.1:80:80 can specify the IP monitored by the host, indicating 127.0.0.1:8080 - > 80 / TCP
                        # -p 8022:22/tcp can specify the port type, which means 0.0.0.0:8022 - > 22 / TCP
                        # -p 3050:8050/udp means 0.0.0:3050 - > 8050 / UDP
                        # -p 9000:9000/sctp means 0.0.0:9000 - > 9000 / SCTP
--expose list           # Port or port range of exposed container, format: - expose port[-port][/type],
                        # --expose 80 indicates the port 80 of the exposed container. The default is TCP
                        # --expose 0-65535 port range of exposed container 0-65535
                        # --expose 8080/udp can specify the port type
-P, --publish-all       # Publish -- expose exposed ports all ports to the host, and the host will map randomly generated ports

--name string           # Specify container name
-h, --hostname string   # Specify the host name of the container (the container ID is used as the host name by default)

-w, --workdir string    # The working directory in the container after startup, such as: - w /root (if the directory does not exist, it will be created automatically)
-v, --volume list       # Bind the mount volume, map the local directory to the container, format: - v host_dir_path:container_dir_path, such as:
                        # -v /my_dir:/root/my_dir will be created automatically if the local directory of the host or the directory in the container does not exist
                        
-u, --user string       # Use the specified user identity (the user must exist), format: - U < name|uid > [: < group|gid >]

--mac-address string    # Specify the MAC address of the container, such as: - MAC address 92: d0: c6:0a: 29:33
--network network       # Specify the network to which the container is connected (you can create a network first, then use this network and set a fixed IP address)
--ip string             # Specify the IPv4 address of the container, such as: - ip=172.30.100.104
--ip6 string            # Specify the IPv6 address of the container, such as: - ip6=2001:db8::33
--dns list              # Set custom DNS, such as: - dns=8.8.8.8 --dns=119.29.29.29

--rm                    # Automatically delete after container stops (exits)

--restart string        # The restart strategy after the container exits, which can take the following values:
                        # no container does not restart automatically when exiting (default setting)
                        # On failure [: Max retries] restart only when the container exits in a non-0 state. Optionally, limit the maximum number of restarts
                        # Unless explicitly stopped or Docker itself stops or restarts, restart the container.
                        # Always restarts the container regardless of the exit state. When always is specified, 
                        #                           The Docker daemon will attempt to restart the container indefinitely.
                        #                           Regardless of the current state of the container, the container will always start when the daemon starts.

--entrypoint string     # Replace the default ENTRYPOINT executable file in the image. The file must be an executable file in the container immediately, such as: - entrypoint /bin/sh
[COMMAND] [ARG...]      # Concatenate the commands and parameters after the IMAGE image name

Restart policy: restart-policies—restart

ENTRYPOINT and [COMMAND] [ARG...] Differences between:

  • If there is an entry point command file specified by ENTRYPOINT, this file will be executed when the container starts, and the [COMMAND] [ARG...] after the image name will be passed to ENTRYPOINT as a parameter list, that is, $ENTRYPOINT [COMMAND] [ARG...].
  • If there is no ENTRYPOINT, the [COMMAND] [ARG...] after the image will be the command executed when the container starts, that is, $COMMAND [ARG...].

After the process of the container start command (ENTRYPOINT or [COMMAND] [ARG...]) is executed, the life cycle of the container will end, that is, the container will stop (exit).

Command example:

# Run the container in the background and map TCP ports 0.0.0.0:80 - > 80 / TCP
docker run -d -p 80:80 docker/getting-started

# Allocate the terminal and keep the input open. When the container exits, it will be deleted automatically. After startup, execute / bin/sh
docker run -it --rm ubuntu /bin/sh

# Set the change variable and output all environment variables after startup
docker run -it --rm -e HELLO=world -e HOME ubuntu env

# Run the python image container, the container runs in the background, and the container always restarts automatically,
# The current directory of the host machine is mapped to / root/test in the container, and the working directory of the container is switched to / root/test,
# Mapping port 0.0.0.0:8000 - > 8000 / TCP,
# After startup, execute the command python3 - M http server 8000
docker run -d \
           --restart always \
           -v $(pwd):/root/test -w /root/test \
           -p 8000:8000 \
           python \
           python3 -m http.server 8000

Help information:

$ docker run --help

Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container

Options:
      --add-host list                  Add a custom host-to-IP mapping
                                       (host:ip)
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16            Block IO (relative weight),
                                       between 10 and 1000, or 0 to
                                       disable (default 0)
      --blkio-weight-device list       Block IO weight (relative device
                                       weight) (default [])
      --cap-add list                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the
                                       container
      --cgroupns string                Cgroup namespace to use
                                       (host|private)
                                       'host':    Run the container in
                                       the Docker host's cgroup namespace
                                       'private': Run the container in
                                       its own private cgroup namespace
                                       '':        Use the cgroup
                                       namespace as configured by the
                                                  default-cgroupns-mode
                                       option on the daemon (default)
      --cidfile string                 Write the container ID to the file
      --cpu-period int                 Limit CPU CFS (Completely Fair
                                       Scheduler) period
      --cpu-quota int                  Limit CPU CFS (Completely Fair
                                       Scheduler) quota
      --cpu-rt-period int              Limit CPU real-time period in
                                       microseconds
      --cpu-rt-runtime int             Limit CPU real-time runtime in
                                       microseconds
  -c, --cpu-shares int                 CPU shares (relative weight)
      --cpus decimal                   Number of CPUs
      --cpuset-cpus string             CPUs in which to allow execution
                                       (0-3, 0,1)
      --cpuset-mems string             MEMs in which to allow execution
                                       (0-3, 0,1)
  -d, --detach                         Run container in background and
                                       print container ID
      --detach-keys string             Override the key sequence for
                                       detaching a container
      --device list                    Add a host device to the container
      --device-cgroup-rule list        Add a rule to the cgroup allowed
                                       devices list
      --device-read-bps list           Limit read rate (bytes per second)
                                       from a device (default [])
      --device-read-iops list          Limit read rate (IO per second)
                                       from a device (default [])
      --device-write-bps list          Limit write rate (bytes per
                                       second) to a device (default [])
      --device-write-iops list         Limit write rate (IO per second)
                                       to a device (default [])
      --disable-content-trust          Skip image verification (default true)
      --dns list                       Set custom DNS servers
      --dns-option list                Set DNS options
      --dns-search list                Set custom DNS search domains
      --domainname string              Container NIS domain name
      --entrypoint string              Overwrite the default ENTRYPOINT
                                       of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --gpus gpu-request               GPU devices to add to the
                                       container ('all' to pass all GPUs)
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check
                                       (ms|s|m|h) (default 0s)
      --health-retries int             Consecutive failures needed to
                                       report unhealthy
      --health-start-period duration   Start period for the container to
                                       initialize before starting
                                       health-retries countdown
                                       (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to
                                       run (ms|s|m|h) (default 0s)
      --help                           Print usage
  -h, --hostname string                Container host name
      --init                           Run an init inside the container
                                       that forwards signals and reaps
                                       processes
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local
                                       addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (e.g.,
                                       92:d0:c6:0a:29:33)
  -m, --memory bytes                   Memory limit
      --memory-reservation bytes       Memory soft limit
      --memory-swap bytes              Swap limit equal to memory plus
                                       swap: '-1' to enable unlimited swap
      --memory-swappiness int          Tune container memory swappiness
                                       (0 to 100) (default -1)
      --mount mount                    Attach a filesystem mount to the
                                       container
      --name string                    Assign a name to the container
      --network network                Connect a container to a network
      --network-alias list             Add network-scoped alias for the
                                       container
      --no-healthcheck                 Disable any container-specified
                                       HEALTHCHECK
      --oom-kill-disable               Disable OOM Killer
      --oom-score-adj int              Tune host's OOM preferences (-1000
                                       to 1000)
      --pid string                     PID namespace to use
      --pids-limit int                 Tune container pids limit (set -1
                                       for unlimited)
      --platform string                Set platform if server is
                                       multi-platform capable
      --privileged                     Give extended privileges to this
                                       container
  -p, --publish list                   Publish a container's port(s) to
                                       the host
  -P, --publish-all                    Publish all exposed ports to
                                       random ports
      --pull string                    Pull image before running
                                       ("always"|"missing"|"never")
                                       (default "missing")
      --read-only                      Mount the container's root
                                       filesystem as read only
      --restart string                 Restart policy to apply when a
                                       container exits (default "no")
      --rm                             Automatically remove the container
                                       when it exits
      --runtime string                 Runtime to use for this container
      --security-opt list              Security Options
      --shm-size bytes                 Size of /dev/shm
      --sig-proxy                      Proxy received signals to the
                                       process (default true)
      --stop-signal string             Signal to stop a container
                                       (default "SIGTERM")
      --stop-timeout int               Timeout (in seconds) to stop a
                                       container
      --storage-opt list               Storage driver options for the
                                       container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -t, --tty                            Allocate a pseudo-TTY
      --ulimit ulimit                  Ulimit options (default [])
  -u, --user string                    Username or UID (format:
                                       <name|uid>[:<group|gid>])
      --userns string                  User namespace to use
      --uts string                     UTS namespace to use
  -v, --volume list                    Bind mount a volume
      --volume-driver string           Optional volume driver for the
                                       container
      --volumes-from list              Mount volumes from the specified
                                       container(s)
  -w, --workdir string                 Working directory inside the container

2.3 list containers: docker container ls

Can be abbreviated as docker ps , lists the containers that have been created.

Help information:

$ docker container ls --help

Usage:  docker container ls [OPTIONS]

List containers

Aliases:
  ls, ps, list

Options:
  -a, --all             Show all containers (default shows just running)
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print containers using a Go template
  -n, --last int        Show n last created containers (includes all states) (default -1)
  -l, --latest          Show the latest created container (includes all states)
      --no-trunc        Don't truncate output
  -q, --quiet           Only display container IDs
  -s, --size            Display total file sizes

Command example:

# List running containers
$ docker ps

# List all containers
$ docker ps -a

2.4 delete container: docker container rm

Can be abbreviated as docker rm.

# Command format
Usage:  docker container rm [OPTIONS] CONTAINER [CONTAINER...]

# Command example
$ docker rm mycontainer

2.5 start container: docker container start

Can be abbreviated as docker start.

# Command format
Usage:  docker container start [OPTIONS] CONTAINER [CONTAINER...]

# Command example
$ docker start mycontainer

2.6 stop container: docker container stop

Can be abbreviated as docker stop.

# Command format
Usage:  docker container stop [-t/--time SEC] CONTAINER [CONTAINER...]

# Command example: stop the container and wait for 5 seconds. If it has not been stopped, it will be killed directly
$ docker stop -t 5 mycontainer

# Command example: stop container (default - t=10)
$ docker stop mycontainer

2.7 restart container: docker container restart

Can be abbreviated as docker restart.

# Command format
Usage:  docker container restart [-t/--time SEC] CONTAINER [CONTAINER...]

# Command example
$ docker restart mycontainer

2.8 terminate container: docker container kill

Can be abbreviated as docker kill.

# Command format
Usage:  docker container kill [OPTIONS] CONTAINER [CONTAINER...]

# Command example
$ docker kill mycontainer

2.9 display container process: docker container top

Can be abbreviated as docker top , displays the processes running in the container.

# Command format
Usage:  docker container top CONTAINER [ps OPTIONS]

# Command example
docker top mycontainer

2.10 display container resource usage: docker container stats

Can be abbreviated as docker stats.

Command help:

$ docker stats --help

Usage:  docker stats [OPTIONS] [CONTAINER...]

Display a live stream of container(s) resource usage statistics

Options:
  -a, --all             Show all containers (default shows just running)
      --format string   Pretty-print images using a Go template
      --no-stream       Disable streaming stats and only pull the first result
      --no-trunc        Do not truncate output

Command example:

# Displays the running container resource usage
$ docker stats

# Display the results of the first running resource (only the results of the first running resource are displayed)
$ docker stats --no-stream

# Show all container resource usage
$ docker stats -a

# Displays the resource usage of the specified container
$ docker stats mycontainer

2.11 rename container: docker container rename

Can be abbreviated as docker rename.

# Command format
Usage:  docker container rename CONTAINER NEW_NAME

# Command example
$ docker rename my_container my_new_container

2.12 run the command in the container: docker container exec

Can be abbreviated as docker exec.

Help information:

$ docker container exec --help

Usage:  docker container exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

Options:
  -d, --detach               Detached mode: run command in the background
      --detach-keys string   Override the key sequence for detaching a container
  -e, --env list             Set environment variables
      --env-file list        Read in a file of environment variables
  -i, --interactive          Keep STDIN open even if not attached
      --privileged           Give extended privileges to the command
  -t, --tty                  Allocate a pseudo-TTY
  -u, --user string          Username or UID (format: <name|uid>[:<group|gid>])
  -w, --workdir string       Working directory inside the container

Command example:

# Run the command in the container, assign a terminal and keep the input open
$ docker exec -it mycontainer /bin/sh

# assign work directory
$ docker exec -it -w /root mycontainer pwd

# Run commands in the background of the container
$ docker exec -d mycontainer COMMAND [ARG...]

2.13 copying files between container and local: docker container cp

Can be abbreviated as docker cp , it supports the mutual replication of files / folders between the container and the local host.

# Command format
Usage:  docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
        docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

# Copy from the previous parameter path to the following parameter path. The path in the CONTAINER needs to be prefixed with CONTAINER:

Command example:

# Copy the / bin folder in the container to the local host/ Bin directory
$ docker cp mycontainer:/bin ./bin

# Local to the host/ demo. Copy the JPG file to the / root / directory in the container, and the name will not change
$ docker cp ./demo.jpg mycontainer:/root/

# Local to the host/ demo. Copy the JPG file to the / root / directory in the container and name it AA jpg
$ docker cp ./demo.jpg mycontainer:/root/aa.jpg

# Local to the host/ aa_ Copy the dir folder to the / root / directory in the container (save as / root/aa_dir)
$ docker cp ./aa_dir mycontainer:/root/

2.14 list container port mapping: docker container port

Can be abbreviated as docker port.

# Command format
Usage:  docker container port CONTAINER [PRIVATE_PORT[/PROTO]]

# Command example
$ docker port mycontainer

2.15 display container details: docker container inspect

Can be abbreviated as docker inspect.

# Command format
Usage:  docker container inspect [OPTIONS] CONTAINER [CONTAINER...]

# Command example
$ docker inspect mycontainer

# Query the specified field, query the [{"Id": *}] Field
$ docker inspect -f "{{.Id}}" mycontainer
a457a7...

# Query field [{"Config": {"Env": *}}]
$ docker inspect -f "{{.Config.Env}}" mycontainer
[PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

# Query field [{"Config": {"Cmd": *}}]
$ docker inspect -f "{{.Config.Cmd}}" mycontainer
[/bin/sh -c #(nop)  CMD ["bash"]]

# Query field [{"State": {"Status": *}]
$ docker inspect -f "{{.State.Status}}" mycontainer
exited

# Querying container restart policy [{hostconfig ": {restartpolicy: *}]
$ docker inspect -f "{{.HostConfig.RestartPolicy}}" mycontainer

2.16 export container file system: docker container export

Can be abbreviated as docker export , package the file system of the container into a tar archive file for export, which can be used after export docker [image] import ]Import as a new image.

# Command format
Usage:  docker export [OPTIONS] CONTAINER

# The export container is saved as mycontainer Tar (export to stdout by default)
$ docker export -o mycontainer.tar mycontainer
# or
$ docker export mycontainer > mycontainer.tar

docker import command:

# Command format
Usage:  docker import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]

# Import container file system to create a new image
$ docker import mycontainer.tar image_name:tag
# or
$ cat mycontainer.tar | docker import - image_name:tag
# or
$ docker import - image_name:tag < test.tar

2.17 update container configuration: docker container update

Can be abbreviated as docker update , update the container configuration, such as CPU, memory usage limit, restart strategy, etc.

Help information:

$ docker container update --help

Usage:  docker container update [OPTIONS] CONTAINER [CONTAINER...]

Update configuration of one or more containers

Options:
      --blkio-weight uint16        Block IO (relative weight), between 10
                                   and 1000, or 0 to disable (default 0)
      --cpu-period int             Limit CPU CFS (Completely Fair
                                   Scheduler) period
      --cpu-quota int              Limit CPU CFS (Completely Fair
                                   Scheduler) quota
      --cpu-rt-period int          Limit the CPU real-time period in
                                   microseconds
      --cpu-rt-runtime int         Limit the CPU real-time runtime in
                                   microseconds
  -c, --cpu-shares int             CPU shares (relative weight)
      --cpus decimal               Number of CPUs
      --cpuset-cpus string         CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string         MEMs in which to allow execution (0-3, 0,1)
      --kernel-memory bytes        Kernel memory limit
  -m, --memory bytes               Memory limit
      --memory-reservation bytes   Memory soft limit
      --memory-swap bytes          Swap limit equal to memory plus swap:
                                   '-1' to enable unlimited swap
      --pids-limit int             Tune container pids limit (set -1 for
                                   unlimited)
      --restart string             Restart policy to apply when a
                                   container exits

Command example:

# The container is set to always restart automatically
$ docker update --restart always mycontainer

2.18 create new image after container change: docker container commit

Can be abbreviated as docker commit , according to the change of the container, submit it as a new image, which can be used after submission docker [image] pull Push the image to the registration server.

Usage:  docker container commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

# Commit container image changes and create image_name:tag Image
$ docker commit mycontainer image_name:tag

2.19 pause container: docker container pause

Can be abbreviated as docker pause.

# Command format
Usage:  docker container pause CONTAINER [CONTAINER...]

# Command example
docker pause mycontainer

2.20 recovery container: docker container unpause

Can be abbreviated as docker unpause.

# Command format
Usage:  docker container unpause CONTAINER [CONTAINER...]

# Command example
docker unpause mycontainer

3. Network management: docker network

docker network Help information:

$ docker network     

Usage:  docker network COMMAND

Manage networks

Commands:
  connect     Connect a container to a network
  create      Create a network
  disconnect  Disconnect a container from a network
  inspect     Display detailed information on one or more networks
  ls          List networks
  prune       Remove all unused networks
  rm          Remove one or more networks

Run 'docker network COMMAND --help' for more information on a command.

3.1 create network: docker network create

Help documentation:

docker network create --help

Usage:  docker network create [OPTIONS] NETWORK

Create a network

Options:
      --attachable           Enable manual container attachment
      --aux-address map      Auxiliary IPv4 or IPv6 addresses used by Network driver (default map[])
      --config-from string   The network from which to copy the configuration
      --config-only          Create a configuration only network
  -d, --driver string        Driver to manage the Network (default "bridge")
      --gateway strings      IPv4 or IPv6 Gateway for the master subnet
      --ingress              Create swarm routing-mesh network
      --internal             Restrict external access to the network
      --ip-range strings     Allocate container ip from a sub-range
      --ipam-driver string   IP Address Management Driver (default "default")
      --ipam-opt map         Set IPAM driver specific options (default map[])
      --ipv6                 Enable IPv6 networking
      --label list           Set metadata on a network
  -o, --opt map              Set driver specific options (default map[])
      --scope string         Control the network's scope
      --subnet strings       Subnet in CIDR format that represents a network segment

Command example:

# Create a network (the default driver management is -- driver=bridge)
$ docker network create \
    --subnet=192.168.0.0/16 \       # Subnet segment
    --ip-range=192.168.100.0/24 \   # IP address range (it must be within the range of subnet. If it is not specified, it will be consistent with subnet)
    --gateway=192.168.100.100 \     # subnet gateway (multiple subnets and gateways can be set)
    mynet                           # Network name

# Specify the network and fixed IP address when creating the container
docker run --rm -it --network=mynet --ip=192.168.100.200 busybox ifconfig

(32-bit) IP address range Description:

  • 192.168.0.0/16 indicates that it starts with 192.168.0.0, and the first 16 bits remain unchanged, that is, it indicates that the range is 192.168.0.0 ~ 192.168.255.255
  • 192.168.100.0/24 indicates that it starts with 192.168.100.0, and the first 24 bits remain unchanged, that is, it indicates that the range is 192.168.100.0 ~ 192.168.100.255

If the host network supports IPv6, but the container network does not support IPv6, you can try to enable IPv6 with Docker:

(0) confirm that the host has IPv6 address:

# View the host (eth0) inet6 address
$ ifconfig

(1) Edit VIM / etc / docker / daemon JSON (create if the file does not exist), input:

{
    "ipv6": true,
    "fixed-cidr-v6": "fd00::/80",
    "experimental": true,
    "ip6tables": true
}

(2) Restart Docker Engine:

# Restart docker service
$ systemctl restart docker

# View the inet6 address assigned by docker0
$ ifconfig

(3) Create a container to test IPv6:

# Force IPv6 PING
$ docker run --rm -it busybox ping -6 -c 3 ipv6-test.com

# Check whether the container is assigned inet6 address
$ docker run --rm -it busybox ifconfig

3.2 list network: docker network ls

$ docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
bc3*********   bridge    bridge    local
876*********   host      host      local
ff3*********   mynet     bridge    local
797*********   none      null      local

3.3 network connection: docker network connect

Help information:

docker network connect --help   

Usage:  docker network connect [OPTIONS] NETWORK CONTAINER

Connect a container to a network

Options:
      --alias strings           Add network-scoped alias for the container
      --driver-opt strings      driver options for the network
      --ip string               IPv4 address (e.g., 172.30.100.104)
      --ip6 string              IPv6 address (e.g., 2001:db8::33)
      --link list               Add link to another container
      --link-local-ip strings   Add a link-local address for the container

Command example:

# Connect the container (mycontainer) to the network (mynet) and specify the fixed IP
$ docker network connect --ip=192.168.100.123 mynet mycontainer

# After the connection is successful, there will be one more network (eth1) in the container
$ docker exec -it mycontainer ifconfig

3.4 network disconnection: docker network disconnect

# Command format, - s indicates forced disconnection
Usage:  docker network disconnect [-f/--force] NETWORK CONTAINER

# Command example: disconnect the container (mycontainer) from the network (mynet)
$ docker network disconnect mynet mycontainer

# After the disconnection is successful, there will be one less network (eth1) in the container
$ docker exec -it mycontainer ifconfig

3.5 remove network: docker network rm/prune

# Command format
Usage:  docker network rm NETWORK [NETWORK...]
Usage:  docker network prune [OPTIONS]

# Command example: remove the network (mynet). Disconnect the network connection with the container before removing
$ docker network rm mynet

# Remove all networks not in use
$ docker network prune

3.6 network details: docker network inspect

Help information:

docker network inspect --help

Usage:  docker network inspect [OPTIONS] NETWORK [NETWORK...]

Display detailed information on one or more networks

Options:
  -f, --format string   Format the output using the given Go template
  -v, --verbose         Verbose output for diagnostics

Command example:

# View network (mynet) details
$ docker network inspect mynet

# View ID
$ docker network inspect -f {{.Id}} mynet  

# View containers connected to this network (mynet)
$ docker network inspect -f {{.Containers}} mynet

4. Volume management: docker volume

docker volume Help information:

$ docker volume

Usage:  docker volume COMMAND

Manage volumes

Commands:
  create      Create a volume
  inspect     Display detailed information on one or more volumes
  ls          List volumes
  prune       Remove all unused local volumes
  rm          Remove one or more volumes

Run 'docker volume COMMAND --help' for more information on a command.

4.1 create volume: docker volume create

Create a volume. When creating a container, map the volume (- v) to the directory in the container (similar to mapping the local directory of the host to the directory in the container), so that multiple containers can share files with each other.

Help information:

$ docker volume create --help

Usage:  docker volume create [OPTIONS] [VOLUME]

Create a volume

Options:
  -d, --driver string   Specify volume driver name (default "local")
      --label list      Set metadata for a volume
  -o, --opt map         Set driver specific options (default map[])

Command example:

# Create a volume named hello
$ docker volume create hello

# When creating a container, the volume (hello) is mapped to the / world Directory of the container (if not, it is automatically created)
$ docker run --rm -it -v hello:/world -w /world busybox touch hi.txt

# Create another container to map the volume and view the files in the volume
$ docker run --rm -it -v hello:/root/hi alpine ls /root/hi
hi.txt

4.2 list volume: docker volume ls

# List all volumes
$ docker volume ls
DRIVER    VOLUME NAME
local     hello

4.3 volume details: docker volume inspect

# Query volume details
$ docker volume inspect volume_name

4.4 delete volume: docker volume rm/prune

# remove volume
$ docker volume rm volume_name

# Delete all unused volumes locally
$ docker volume prune

5. System management: docker system

docker system Help information:

$ docker system

Usage:  docker system COMMAND

Manage Docker

Commands:
  df          Show docker disk usage
  events      Get real time events from the server
  info        Display system-wide information
  prune       Remove unused data

Run 'docker system COMMAND --help' for more information on a command.

5.1 disk usage: docker system df

Display disk usage status:

$ docker system df
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          8         1         1.009GB   1.009GB (100%)
Containers      1         1         1.397MB   0B (0%)
Local Volumes   1         0         0B        0B
Build Cache     2         0         0B        0B

5.2 system information: docker system info

Display system information: number of containers, number of images, version information, operating system, CPU architecture and other information

$ docker system info

5.3 removing data: docker system prune

Remove unused data:

$ docker system prune
WARNING! This will remove:
  - all stopped containers
  - all networks not used by at least one container
  - all dangling images
  - all dangling build cache

Are you sure you want to continue? [y/N]

6. Build image file: Dockerfile

Dockerfile is a description file used by docker build to build an image. It is composed of a series of instructions. After each instruction is run, a layer will be generated in the image.

Official documents:

Dockerfile common instructions:

  1. FROM : specify a mirror as the base mirror. If it is not based on any image, you can reference the blank image FROM scratch.
  2. RUN : when constructing the image, run the command in the (layer) container. After the instruction is executed, submit the container change to form a new layer.
  3. CMD : after the image is built, create a container. The default command is executed when the container is started.
  4. LABEL : add metadata to the image, such as author, version, description, etc.
  5. ENV : set the environment variable in the container. The environment variable set by ENV can be used in the ADD, COPY, ENV, EXPOSE, FROM, LABEL, STOPSIGNAL, USER, VOLUME, WORKDIR, ONBUILD and other instructions (the instructions run in the image container and cannot reference the local environment variable of the host).
  6. ARG : define a variable (you can specify the default value). When you execute the docker build command, you can pass in parameters to assign values to this variable (- - build ARG < ARG_NAME > = < value >), and subsequent instructions can use ${ARG_NAME} to reference the value of the variable. Unlike ENV, ARG set variables are not saved to the final image, and ARG variables are only valid during construction (including in the container executing the RUN instruction).
  7. COPY : copy files / folders to the mirrored (new tier) file system.
  8. ADD : add files / folders to the mirrored (new tier) file system (support automatic decompression).
  9. ENTRYPOINT : the command executed when the container is started. With this parameter, the content of CMD instruction will be passed to the ENTRYPOINT command as a parameter.
  10. EXPOSE : the (TCP/UDP) port that is intended to be published (exposed) when the container is created.
  11. VOLUME : automatically create volumes when creating containers and mount them to the specified mount point.
  12. USER : change the user identity of running RUN, CMD, ENTRYPOINT and other instructions and the default user identity when the container is started. The user must be created in the container. If no user is specified, the default is root.
  13. WORKDIR : change the working directory when the following instruction runs (the directory in the container, which is also the default working directory when running the container). It can be a relative path (relative to the path of the previous WORKDIR instruction). The default path is /.
  14. ONBUILD : the instruction triggered when this image is referenced by other dockerfiles as the basic image (such as RUN, COPY, etc.). This build is not executed, but executed in the FROM instruction when referenced by other dockerfiles.
  15. SHELL : override the shell used by default when executing commands. The default is ["/ bin/sh", "-c"] for Linux and ["cmd", "/S", "/C"] for Windows.
  16. STOPSIGNAL : set the system call signal (container stop signal) that will be sent to the container to exit the container. The default is SIGTERM.
  17. HEALTHCHECK : container health check instruction, which tells Docker how to test the container to check whether it is still working.

Simple try (build a python image using alpine as the base image):

# Dockerfile file content
$ cat Dockerfile
FROM alpine
RUN apk update && apk add python3
CMD python3

# Build an image, save the image name as alpine py, and the context path during construction is the current path (read. / Dockerfile)
$ docker build -t alpine-py .

# After the construction is successful, view the image
$ docker images                    
REPOSITORY  TAG       IMAGE ID       CREATED         SIZE
alpine-py   latest    3129997e5558   3 hours ago     53.5MB
alpine      latest    8e1d7573f448   2 months ago    5.33MB

# Create container
$ docker run --rm -it alpine-py   
Python 3.9.7 (default, Nov 24 2021, 21:15:59) 
[GCC 10.3.1 20211027] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

6.1 FROM

FROM : specify a mirror as the base mirror. If it is not based on any image, you can reference the blank image FROM scratch.

Dockerfile must start with the FROM instruction (ARG can be used to declare variables before FROM). In the dockerfile file, other instructions may not exist, but the FROM instruction must exist.

Instruction format:

FROM [--platform=<platform>] <image> [AS <name>]
# or
FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]
# or
FROM [--platform=<platform>] <image>[@<digest>] [AS <name>]

Examples of instructions:

FROM alpine
ARG VERSION=latest
FROM alpine:${VERSION}

6.2 RUN

RUN : when constructing the image, run the command in the (layer) container. After the instruction is executed, submit the container change to form a new layer.

The RUN instruction will first create a container, then RUN the command in the container, and then submit the changes to form a new layer.

If there are multiple RUN instructions, each instruction will create a new container (using the latest current image) to RUN the command, so the commands of multiple RUN instructions will RUN in different contexts (the file system will follow).

In order to avoid creating multiple file system layers, it is recommended to combine multiple RUN instructions. You can use the continuation character \ to wrap the command.

RUN has two forms:

  • Run < command > (in shell form, the command runs in the shell, the default is / bin/sh -c for Linux and CMD / S / C for Windows)
  • RUN ["executable", "param1", "param2"] (exec form)

Example of RUN instruction:

RUN apt update && apt install -y vim

or

FROM ubuntu

RUN apt update && \
    apt install -y vim

Run the command in exec form:

RUN ["echo", "Hello World"]

# Run the command in the form of exec. The parameters will be parsed into a JSON array. Double quotation marks (") must be used around each parameter instead of single quotation marks (')

Unlike the shell form, the exec form does not call shell commands, but runs directly, which means that normal shell processing will not occur in the exec form. For example, RUN ["echo", "$HOME"] does not replace $HOME with the corresponding environment variable value, and uses literal values directly. To run commands in the form of exec and process them in a shell, you can use exec to run a shell first, and then the shell runs commands, for example: RUN ["sh", "-c", "echo $HOME"].

FROM ubuntu

ENV NAME=test
WORKDIR /root/${NAME}

# Call the default shell, / bin/sh -c "touch \"sh_${NAME}.txt \ "", the file will be created: / root/sh_test.txt
RUN touch "sh_${NAME}.txt"

# Without calling the shell, the file: 'exec' will be created_$ {NAME}. txt'
RUN ["touch", "exec_${NAME}.txt"]

# First run a shell and the file will be created: bash_test.txt
RUN ["/bin/bash", "-c", "touch bash_${NAME}.txt"]

# Output: bash_test.txt 'exec_${NAME}.txt'   sh_test.txt
CMD ls

Build test:

$ docker build -t test  .
...

$ docker run --rm -it test
 bash_test.txt	'exec_${NAME}.txt'   sh_test.txt

6.3 CMD

CMD : after the image is built, create a container. The default command is executed when the container is started.

The RUN instruction runs during the docker build, and the CMD instruction runs when the container starts (docker run/start) (RUN as a command or pass as a parameter to ENTRYPOINT). There can only be one CMD instruction in Dockerfile. If there are multiple CMD instructions, the last one will take effect.

CMD instruction has three forms:

  • CMD ["executable", "param1", "param2"] (exec form, which is the preferred form)
  • CMD ["param1", "param2"] (if there is an ENTRYPOINT, it is the default parameter of ENTRYPOINT)
  • CMD command Param1 param2 (in the form of sell, the command will be run with / bin/sh -c "command param1 param2")

In the same form as the RUN instruction, the exec form will not call the shell command, that is, normal shell processing will not occur. For example, CMD ["echo", "$HOME"] does not replace $HOME with the corresponding environment variable value, and uses literal values directly. To RUN commands in the form of exec and conduct shell processing, you can use exec to RUN a shell first, and then the shell runs commands, for example: CMD ["sh", "-c", "echo $HOME"]. Like the shell form, here is the shell for environment variable extension, not docker.

If CMD is used to provide default parameters for ENTRYPOINT or run in the form of exec, the instruction should be specified in JSON array format, and the word must be enclosed in double quotation marks (").

Run in the form of shell. Since a shell process is run first and then the command is run in the sub process, there may be two processes (different systems may be different). Run in exec mode. Since it is run directly (in the current process), there will be only one process.

shell form example:

FROM ubuntu
CMD "top" "-d" "1" "-n" "5"
$ docker build -t test_image . 

# There are 2 processes
$ docker run --rm -it test_image
...
PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                          
  1 root      20   0    2060    476    408 S   0.0   0.0   0:00.01 sh                                               
  8 root      20   0    5704   2524   2120 R   0.0   0.1   0:00.00 top 

Example of exec form:

FROM ubuntu
CMD ["top", "-d", "1", "-n", "5"]
$ docker build -t test_image . 

# Only 1 process
$ docker run --rm -it test_image 
...
PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                          
  1 root      20   0    5736   2608   2220 R   0.0   0.1   0:00.01 top   

How Linux exec runs commands:

When the command is run in exec mode, a new shell will not be started (no new process will be created), but the current shell process will be replaced with the executed command (the PID remains unchanged), and the context of the old process will be cleaned up. Other commands after the exec command will not be executed. For example, open a shell terminal and run the exec ls command. After running, the terminal will exit. This is because the process running the exec ls command "replaces" the original shell terminal process. After the command ends, the terminal exits.

6.4 LABEL

LABEL : add metadata to the image, such as author, version, description, etc. Automatically inherit the label of the parent image (FROM), and the label with the same name will overwrite the former.

Instruction format:

LABEL <key>=<value> <key>=<value> <key>=<value> ...

Examples of instructions:

LABEL "com.example.vendor"="ACME Incorporated"
LABEL com.example.label-with-value="foo"
LABEL version="1.0"
LABEL description="This text illustrates \
that label-values can span multiple lines."

# Multiple labels can be added to a single instruction
LABEL multi.label1="value1" multi.label2="value2" other="value3"

LABEL multi.label1="value1" \
      multi.label2="value2" \
      other="value3"

6.5 ENV

ENV : set the environment variable in the container, and it can be used in subsequent containers that execute the RUN instruction. The environment variables set by ENV can be used in the ADD, COPY, ENV, EXPOSE, FROM, LABEL, STOPSIGNAL, USER, VOLUME, WORKDIR, ONBUILD and other instructions (the instructions RUN in the image container and cannot reference the local environment variables of the host).

Instruction format:

ENV <key>=<value> <key>=<value> <key>=<value> ...

Examples of instructions:

ENV MY_NAME="John Doe"
ENV MY_DOG=Rex\ The\ Dog
ENV MY_CAT=fluffy

# Multiple can be set at one time
ENV MY_NAME="John Doe" \
    MY_DOG=Rex\ The\ Dog \
    MY_CAT=fluffy

The environment variable set by ENV saves persistence in the image and container. If you need to use environment variables during construction (not saved to the image), you can set the environment variables at the session level in the RUN instruction (RUN heelo = World & & echo $Hello) or use the ARG instruction.

6.6 ARG

ARG : define a variable (you can specify the default value). When you execute the docker build command, you can pass in parameters to assign values to this variable (- - build ARG < ARG_NAME > = < value >), and subsequent instructions can use ${ARG_NAME} to reference the value of the variable. Unlike ENV, ARG set variables are not saved to the final image, and ARG variables are only valid during construction (including in the container executing the RUN instruction).

Instruction format:

ARG <name>[=<default value>]

Examples of instructions:

ARG from_linux=busybox
FROM ${from_linux}

ARG touch_workdir
WORKDIR ${touch_workdir}

ARG Hello=World
RUN touch "${Hello}.txt"

Build:

# Build image
$ docker build \
        --build-arg from_linux=alpine \
        --build-arg touch_workdir=/root \
        -t test_image \
        .
...

# Run container test
$ docker run --rm -it test_image ls /root
World.txt

6.7 COPY

COPY : copy files / folders to the mirrored (new tier) file system.

Instruction format:

COPY [--chown=<user>:<group>] <src>... <dest>
COPY [--chown=<user>:<group>] ["<src>",... "<dest>"]

Paths containing spaces need to use the second format. You can specify the owner of the file added to the image ([-- chown = < user >: < group >])< SRC > indicates the local file / folder directory of the host machine. There can be multiple directories. The last one is < dest >, which indicates the file / folder directory in the container.

< SRC > and < dest > can be absolute or relative paths. If it is a relative PATH, < SRC > relative to docker build [OPTIONS] PATH | URL | - the PATH in the build command, < dest > relative to the directory specified by the build instruction WORKDIR (if the directory does not exist, it will be created automatically).

Examples of instructions:

# Local {path} / AA Txt and {path} / BB Txt file to the {WORKDIR}/abc / directory of the container
COPY aa.txt bb.txt abc/

# Local {path} / AA Txt to the {WORKDIR}/abc / directory and rename it BB txt
COPY aa.txt abc/bb.txt

# Host local AA_ Copy all the contents in the dir folder (aa_dir / *) to the / root / directory of the container
COPY aa_dir /root/

# Host local AA_ Copy the dir folder to the / root / directory of the container and rename it bb_dir
COPY aa_dir /root/bb_dir

# Support * and? wildcard
COPY hom?.txt /root/my_dir/
COPY *.jpg /root/my_dir/

6.8 ADD

ADD : add files / folders to the mirrored (new tier) file system (support automatic decompression).

Instruction format:

ADD [--chown=<user>:<group>] <src>... <dest>
ADD [--chown=<user>:<group>] ["<src>",... "<dest>"]

When adding a file with the ADD instruction, if < SRC > is a tar archive in a recognizable compressed format (identity, gzip, bzip2 or xz), it will be automatically decompressed into a directory. In addition, the basic usage is the same as that of the COPY instruction.

Archive file: test tar. gz

test.tar.gz
|
|--- aa.txt
|
|--- bb_dir

Examples of instructions:

# Generate files after adding:
#   /root/aa.txt
#   /root/bb_dir
ADD test.tar.gz /root/

6.9 ENTRYPOINT

ENTRYPOINT : command executed when the container starts. With this parameter, the content of CMD instruction will be used as the parameter of ENTRYPOINT command.

There are two forms of ENTRYPOINT:

  • ENTRYPOINT ["executable", "param1", "param2"] (exec form, which is the preferred form)
  • Entrypoint command Param1 param2 (in the form of sell, the command will be run with / bin/sh -c "command param1 param2")

Examples of instructions:

FROM ubuntu
ENTRYPOINT ["top", "-d", "1"]
CMD ["-n", "5"]

The default start command of the final container is:

$ exec top -d 1 -n 5

The same form as the RUN and CMD instructions, the exec form will not call shell commands, that is, normal shell processing will not occur. For example, ENTRYPOINT ["echo", "$HOME"] does not replace $HOME with the corresponding environment variable value, and uses literal values directly. To RUN commands in the form of exec and conduct shell processing, you can use exec to RUN a shell first and then RUN commands by the shell, for example: ENTRYPOINT ["sh", "-c", "echo $HOME"], which is the same as the form of shell. Here, the shell extends environment variables instead of docker.

6.9 EXPOSE

EXPOSE : the (TCP/UDP) port that is intended to be published (exposed) when the container is created.

Instruction format:

EXPOSE <port> [<port>/<protocol>...]

The EXPOSE instruction informs the Docker container of the network port it intends to listen on at runtime. You can specify a port to listen to TCP or UDP protocol. If you do not specify a protocol, it defaults to TCP.

The export instruction does not actually publish / listen on the port. It serves as a tacit understanding between the image builder and the user, telling the user the ports to be exposed when using the container, and using the - p parameter to really publish / map the ports when running the container (docker run/create).

Examples of instructions:

EXPOSE 8000/udp 8080/tcp

# You can also expose TCP and UDP on one port at the same time
EXPOSE 80/tcp 80/udp

6.11 VOLUME

VOLUME : automatically create volumes when creating containers and mount them to the specified mount point.

Instruction format:

VOLUME ["/data", "/aa/bb", ...]

Examples of instructions:

FROM busybox

# When you create a container, two volumes are created, mounted to / aa and / bb/cc, respectively
VOLUME ["/aa", "/bb/cc"]

Build run:

# Build image
$ docker build -t test_image .

# Create container
$ docker create test_image
...

# View automatically generated volumes
$ docker volume ls
DRIVER    VOLUME NAME
local     210ec6...
local     f00eac...

# Run the container to view the mount point (the volume will be created every time the container is created, and the volume will be automatically deleted when the -- rm parameter is added to exit the container)
$ docker run --rm -it test_image df -h
Filesystem                Size      Used Available Use% Mounted on
overlay                  58.4G      2.9G     52.5G   5% /
tmpfs                    64.0M         0     64.0M   0% /dev
shm                      64.0M         0     64.0M   0% /dev/shm
/dev/vda1                58.4G      2.9G     52.5G   5% /aa
/dev/vda1                58.4G      2.9G     52.5G   5% /bb/cc
...

6.12 USER

USER : change the user identity of running RUN, CMD, ENTRYPOINT and other instructions and the default user identity when the container is started. The user must be created in the container. If no user is specified, the default is root.

Instruction format:

USER <user|UID>[:<group:GID>]

Examples of instructions:

FROM ubuntu

# Create user first
RUN useradd -m hello

# Use hello user identity
USER hello

# Output the current user name in the RUN instruction: hello
RUN whoami

# The container outputs the current user name at runtime: hello
CMD whoami

6.13 WORKDIR

WORKDIR : change the working directory when the following instruction runs (the directory in the container, which is also the default working directory when running the container). It can be a relative path (relative to the path of the previous WORKDIR instruction). The default path is /.

Instruction format:

WORKDIR /path/to/workdir

If the path does not exist, it will be created automatically. The path provided can be absolute or relative. If it is a relative path, it is relative to the path of the previous WORKDIR.

Examples of instructions:

FROM busybox

# Change path
WORKDIR /a/b

# The output path is / a/b
RUN pwd

# The output path is / a/b
CMD pwd

6.14 ONBUILD

ONBUILD : the instruction triggered when this image is referenced by other dockerfiles as the basic image (such as RUN, COPY, etc.), which is not executed when the current Dockerfile is built, but is executed in the FROM instruction when referenced by other dockerfiles.

Instruction format:

ONBUILD <INSTRUCTION>

Examples of instructions:

ONBUILD RUN cd /root && touch hello.txt
ONBUILD RUN /usr/local/bin/python-build --dir /app/src

6.15 SHELL

SHELL : override the shell used by default when running commands. The default is ["/ bin/sh", "-c"] for Linux and ["cmd", "/S", "/C"] for Windows.

The SHELL instruction can appear multiple times. Each SHELL instruction overrides the previous SHELL instruction and affects all subsequent instructions.

Instruction format:

SHELL ["executable", "parameters"]

Examples of instructions:

FROM ubuntu

# Use ["/ bin/bash", "-c"] as the default shell
SHELL ["/bin/bash", "-c"]

# Will be run as: / bin/bash -c "ls -l"
RUN ls -l

# Will be run as: / bin/bash -c "top"
CMD top 

6.16 STOPSIGNAL

STOPSIGNAL : set the system call signal (container stop signal) that will be sent to the container to exit the container. The default is SIGTERM.

Instruction format:

STOPSIGNAL signal

You can use the -- stop signal parameter to override the default stop signal in the image when docker run/create runs the container.

6.17 HEALTHCHECK

HEALTHCHECK : container health check instruction, which tells Docker how to test the container to check whether it is still working.

There are two forms of the HEALTHCHECK command:

  • HEALTHCHECK [OPTIONS] CMD command
  • HEALTHCHECK NONE (disable any health checks inherited from the underlying mirror)

Tags: Linux Docker Container dockerfile

Posted by creativeimpact on Wed, 23 Feb 2022 02:06:02 +1030