Docker Basics - 1

This article was last updated on: February 7, 2024 pm

mirror image

Get the image

docker pull

View the image information

docker images

docker inspect <images id> # 获取镜像的详细信息

Seek images

docker search

Delete the image

docker rmi

When an image has multiple tags,docker rmi Simply deleting the label specified by the image does not affect the image file
When there is only one tag left in the image, reuse will completely delete the image
Delete all containers of the image before deleting the image

Create an image

2 methods:

  • Based on an existing imagecontainercreate
  • Created from a Dockerfile (recommended)

Create a container based on an existing image

docker commit

-a: Author information
-m: Submit information
-p Pauses the container on commit
-c changelist

Check out and load images

Save outsudo docker save -o ubuntu_16.04.tar ubuntu:16.04

Onboardingsudo docker load --input ubuntu_16.04.tar or sudo docker load < ubuntu_16.04.tar

Import the image and its associated metadata (including tags, etc.)

container

Create a container

To run the container using interactive:sudo docker run -it ubuntu:latest /bin/bash

docker runStandard actions performed in the background:

  1. Check whether the specified image exists locally and download it from the public repository if it does not exist
  2. Take advantage of mirroringcreatecombineinitiateA container
  3. Allocate a file system and mount a layer outside the read-only image layerRead-write layer
  4. From the bridge interface configured from the host hostBridgingA virtual interface to the container.
  5. Configure one from the address pool IP addressGive the container
  6. Executes user-specifiedapplication
  7. After the execution is completeThe container is terminated

Guardian state operation

sudo docker run -d ubuntu /bin/sh -c "while true; do echo hello world; sleep 1; done"

Passdocker logscommand to get the output information of the container:sudo docker -tf logs 2855b4d76ccb

-t: prints the timestamp
-f: Flushes the log to the end
2855b4d76ccb: container id

Terminate the container

sudo docker stop 2855b4d76ccb

View information for all containers:sudo docker ps -a

A container in a terminated state can pass docker start command to restart:sudo docker start 2855b4d76ccb

Restart the container:sudo docker restart 2855b4d76ccb

Enter the container

attach instruction

sudo docker attach 2855b4d76ccb

When multiple windows are attached to the same container at the same time, all windows are displayed synchronously. When a window is blocked by a command, other windows cannot perform the operation.

exec command

sudo docker exec -ti 2855b4d76ccb /bin/bash

Delete the container

sudo docker rm 2855b4d76ccb

-f Force deletion of a running container
-l Delete the container link, but keep the container
-v Delete the data volume mounted by the container

Import/export containers

Export

sudo docker export 2855b4d76ccb > test.tar

You can transfer these files to other machines, and migrate containers via import commands on other machines

Import

cat test.tar | sudo docker import - test/ubuntu:v1.0

docker load Import the image storage file to the local image repository
docker import Import a containersnapshotto the local image library

Distinguish:

Container snapshotsFiles will be discarded allHistory and metadata information(Only the snapshot state of the container at that time is saved), and metadata information such as tags can be respecified when importing.
Mirror storage filesComplete records will be kept, and the volume will also be large.

warehouse

Docker Hub

login

docker login

docker search

docker tag

sudo docker tag ubuntu:14.04 10.0.2.2:5000/test

Automatic creation

Steps:

  1. Log in to Docker Hub and connect GitHub to Docker
  2. Configure auto-creation in Docker Hub: https://hub.docker.com/add/automated-build/caseycui/
  3. Pick a target Web site project (with a Dockerfile) and branch
  4. Specify the location of the Dockerfile and commit the creation
  5. You can then track the status of each creation in the Auto-Create page in Docker Hub.

Create and use private repositories

Use the registry image to create a private repository

sudo docker -d -p 5000:5000 -v /opt/docker/registry/:/tmp/registry registry

The listening port maps to 5000, in the docker container /tmp/registry is mapped to local /opt/docker/registry/ Above.

Manage private repository images

  • MODIFY THE REGISTRYHOST OF THE TAG sudo docker tag ubuntu:latest 172.17.0.1:5000/test
  • Use docker push upload sudo docker push 172.17.0.1:5000/test
  • Use docker pull to download sudo docker pull 172.17.0.1:5000/test

Data management

Two ways:

  • Data Volumes
  • Data Volume Containers

Data volumes

Characteristic:

  • Can be shared and reused across containers
  • Changes to the data volume take effect immediately
  • Updates to data volumes do not affect containers
  • The volume persists until no container is in use

Linux-like mount operation

Mount a host directory as a data volume

sudo docker run -v /src/webapp:/opt/webapp training/webapp python app.py

Load the host’s /src/webapp directory into the container’s /opt/webapp directory.

The host directory must be an absolute path

The default permissions areRead and write(rw), which can be set toread only(ro) /src/webapp:/opt/webapp:ro

Data volume container

Data volume containerIn fact, it is ordinarycontainer, specifically use it to provide data volumes for other container mounts.

  1. Create a data volume container: sudo docker run -it -v /dbdata --name dbdata ubuntu

  2. Used in other containers volumes-from to mount dbdata Data volumes in containers.

    1
    2
    3
    4
    5
    6
    7
    8


    sudo docker run -it --volumes-from dbdata --name db1 ubuntu


    sudo docker run -it --volumes-from dbdata --name db2 ubuntu


    Any of the 3 containers written to the directory, the other containers can see it.
    If the container is deleted, Data volumesIt is not automatically deleted. If you want to delete a data volume, It must be explicitly used when deleting the last container that mounts it docker rm -v command to specify that the associated container be deleted at the same time

Migrate data with data volume containers

backup

sudo docker run --volumes-from dbdata -v $(pwd):/backup --name worker ubuntu tar cvf /backup/backup.tar /dbdata

recover

1
2
sudo docker run -v /dbdata --name dbdata2 ubuntu /bin/bash
sudo docker run --volumes-from dbdata2 -v $(pwd):/backup busybox tar xvf /backup/backup.tar

Network base configuration

Port mapping enables access to containers

sudo docker run -d -p 127.0.0.1:5000:5000/udp training/webapp python app.py

-P: Maps to a random port

Review the port mapping configuration

sudo docker port loving_montalcini

Container interconnect enables communication between containers

The linking system of the container, which creates a tunnel between the source and the receiving container, and the receiving container can see the information specified by the source container.

The connection system is performed according to the name of the container.

In execution docker run If added --rm tag, then the container is deleted immediately after termination. --rm and -d Cannot be used at the same time.

Container interconnect

1
2
sudo docker run -d --name db training/postgres  # 创建一个新的数据库容器 
sudo docker run -d -P --name web --link db:db training/webapp python app.py # --link name:alias alias 是连接的别名

Docker exposes connection information for containers in two ways:

  • environment variable
  • update /etc/hosts file

use env Command to view the environment variables of the web container:

1
2
3
4
5
6
7
8
9
10
11
$ docker exec web env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=62b19d3b5add
DB_PORT=tcp://172.17.0.2:5432
DB_PORT_5432_TCP=tcp://172.17.0.2:5432
DB_PORT_5432_TCP_ADDR=172.17.0.2
DB_PORT_5432_TCP_PORT=5432
DB_PORT_5432_TCP_PROTO=tcp
DB_NAME=/web/db
DB_ENV_PG_VERSION=9.3
HOME=/root

/etc/hosts File:

1
2
3
4
5
6
7
8
9
10
11
12
$ docker exec web cat /etc/hosts

127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

172.17.0.2 db 4288c4f9ad47

172.17.0.3 62b19d3b5add # 本容器

It can also be tested by ping:

1
2
3
4
5
6
7
8
$ docker exec web ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.083 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.054 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.054 ms
64 bytes from 172.17.0.2: icmp_seq=4 ttl=64 time=0.053 ms
64 bytes from 172.17.0.2: icmp_seq=5 ttl=64 time=0.055 ms
64 bytes from 172.17.0.2: icmp_seq=6 ttl=64 time=0.057 ms

Use a Dockerfile to create an image

Basic structure

  • Base image information
  • Maintainer information
  • Image operation instructions
  • Execute instructions when the container starts

directives

FROM

The first instruction must be a FROM directive

MAINTAINER (DEPRECATED)

Develop maintainer information. Can be used later LABEL maintainer="CaseyCui [email protected]"

RUN

Two formats:

  • RUN <command> bashFormat, the command runs in bash, which defaults to Linux /bin/sh -c On Windows yes cmd /S /C
  • RUN ["executable", "param1", "param2"] (with docker exec Execution)

Each RUN command will execute the specified command based on the current image and submit it as a new image.

Best practices:

apt-get installation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
RUN apt-get update && apt-get install -y --no-install-recommends \
aufs-tools \
automake \
build-essential \
curl \
dpkg-sig \
libcap-dev \
libsqlite3-dev \
mercurial \
reprepro \
ruby1.9.1 \
ruby1.9.1-dev \
s3cmd=1.1.* \
&& rm -rf /var/lib/apt/lists/*

apt-get update && apt-get install share

apt-get install -y --no-install-recommends Do not install other recommended packages, -no-install-suggests It can also be added

ruby1.9.1 s3cmd=1.1.* Installs the specified version of the package

rm -rf /var/lib/apt/lists/* Remove package residues

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
## a few minor docker-specific tweaks
## see https://github.com/docker/docker/blob/9a9fc01af8fb5d98b8eec0740716226fadb3735c/contrib/mkimage/debootstrap
RUN set -xe \
\
## https://github.com/docker/docker/blob/9a9fc01af8fb5d98b8eec0740716226fadb3735c/contrib/mkimage/debootstrap#L40-L48
&& echo '#!/bin/sh' > /usr/sbin/policy-rc.d \
&& echo 'exit 101' >> /usr/sbin/policy-rc.d \
&& chmod +x /usr/sbin/policy-rc.d \
\
## https://github.com/docker/docker/blob/9a9fc01af8fb5d98b8eec0740716226fadb3735c/contrib/mkimage/debootstrap#L54-L56
&& dpkg-divert --local --rename --add /sbin/initctl \
&& cp -a /usr/sbin/policy-rc.d /sbin/initctl \
&& sed -i 's/^exit.*/exit 0/' /sbin/initctl \
\
## https://github.com/docker/docker/blob/9a9fc01af8fb5d98b8eec0740716226fadb3735c/contrib/mkimage/debootstrap#L71-L78
&& echo 'force-unsafe-io' > /etc/dpkg/dpkg.cfg.d/docker-apt-speedup \
\
## https://github.com/docker/docker/blob/9a9fc01af8fb5d98b8eec0740716226fadb3735c/contrib/mkimage/debootstrap#L85-L105
&& echo 'DPkg::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };' > /etc/apt/apt.conf.d/docker-clean \
&& echo 'APT::Update::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };' >> /etc/apt/apt.conf.d/docker-clean \
&& echo 'Dir::Cache::pkgcache ""; Dir::Cache::srcpkgcache "";' >> /etc/apt/apt.conf.d/docker-clean \
\
## https://github.com/docker/docker/blob/9a9fc01af8fb5d98b8eec0740716226fadb3735c/contrib/mkimage/debootstrap#L109-L115
&& echo 'Acquire::Languages "none";' > /etc/apt/apt.conf.d/docker-no-languages \
\
## https://github.com/docker/docker/blob/9a9fc01af8fb5d98b8eec0740716226fadb3735c/contrib/mkimage/debootstrap#L118-L130
&& echo 'Acquire::GzipIndexes "true"; Acquire::CompressionTypes::Order:: "gz";' > /etc/apt/apt.conf.d/docker-gzip-indexes \
\
## https://github.com/docker/docker/blob/9a9fc01af8fb5d98b8eec0740716226fadb3735c/contrib/mkimage/debootstrap#L134-L151
&& echo 'Apt::AutoRemove::SuggestsImportant "false";' > /etc/apt/apt.conf.d/docker-autoremove-suggests

set -xe Debug mode, return non-0 (i.e. unsuccessful) and exit

CMD

Three formats are supported:

  • CMD ["executable","param1","param2"] use docker exec execute Recommended way
  • CMD ["param1","param2"] As ENTRYPOINT The default parameters
  • CMD command param1 param2 bash

Specifies the command to execute when starting the container, each Dockerfile can have only one CMD command.

EXPOSE

EXPOSE 80 8443

Exposed port number, for use by interconnected systems. Passable at startup -P or -p to specify the mapping

ENV

1
2
3
4
ENV PG_MAJOR 9.3
ENV PG_VERSION 9.3.4
RUN curl -SL http://example.com/postgres-$PG_VERSION.tar.xz | tar -xJC /usr/src/postgress && …
ENV PATH /usr/local/postgres-$PG_MAJOR/bin:$PATH

ADD

recommendOnly in src When using a tar file (automatically unzipped). OTHER TIMES USE COPY. The use of URLs is deprecated.

COPY

COPY <src> <dest> When using src in this example, COPY is recommended

ENTRYPOINT

Two formats:

  • ENTRYPOINT ["executable", "param1", "param2"] exec format
  • ENTRYPOINT command param1 param2 bash format

VOLUME

Create a mount point that can be mounted from the local host or other containers, generally used to store the database and the data that needs to be maintained.

USER

Specify the user name or UID when running the container, subsequently RUN Named User is also used.

When the service does not require administrator privileges, the running user can be specified through this command.

Recommended for temporary administrator privileges gosu , not recommendedsudo

WORKDIR

for follow-up RUN CMD ENTRYPOINT Directive configuration working directory.

ONBUILD

ONBUILD [Dockerilfe 的指令]

Configure the action instructions that are performed when the created image is used as the base image for other newly created images.

use ONBUILD The mirror image of the instruction is recommended to be noted in the tag, such as ruby:1.9-onbuild

Create an image

docker build [选项] 路径

Implement:

  1. Reads a Dockerfile under the specified path, including subdirectories
  2. Send everything under this path to the Docker server
  3. The server creates the image

It is generally recommended that the directory where the Dockerfile is placed is empty

Can pass .dockerignore file to make Docker ignore directories and files under the path.

1
2
3
4
## comment
*/temp*
*/*/temp*
temp?

Examples of directives: sudo docker build -t build_repo/first_image /tmp/docker_builder/


Docker Basics - 1
https://e-whisper.com/posts/20855/
Author
east4ming
Posted on
September 27, 2021
Licensed under