Docker

2024/05/01 Docker 共 12576 字,约 36 分钟

Docker

1、安装

1.1 卸载旧版本

#检查是否安装旧版本
$ sudo rpm -qa | grep docker
#卸载旧版本
$ sudo yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine

1.2 安装yum工具包

#检查是否安装旧版本
$ sudo rpm -qa | grep yum-utils
#安装yum工具包
$ sudo yum install -y yum-utils

1.3 配置仓库源

#查看yum启用的仓库源
$ yum repolist enabled
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.nju.edu.cn
 * updates: mirrors.nju.edu.cn
源标识                                 源名称                             状态
!base/7/x86_64                         CentOS-7 - Base                    10,072
!extras/7/x86_64                       CentOS-7 - Extras                     526
!nginx-stable/7/x86_64                 nginx stable repo                     324
!updates/7/x86_64                      CentOS-7 - Updates                  5,802
repolist: 16,724
# 1. 默认使用国外源,非常非常非常慢!
$ sudo yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo

# 2. 推荐用国内源,丝滑!
$ sudo yum-config-manager \
    --add-repo \
    https://mirrors.ustc.edu.cn/docker-ce/linux/centos/docker-ce.repo

1.4 安装Docker Engine

sudo yum install docker-ce docker-ce-cli containerd.io

1.5 启动与验证docker

$ sudo systemctl enable docker
$ sudo systemctl start docker
$ docker --version

2、镜像

2.1 镜像中心 docker hub

dockerhub官方网站

https://hub-stage.docker.com/

开源镜像站汇总 & 延迟测试工具

http://tvtv.fun/mirrors-list.html

修改镜像源

  1. 编辑 /etc/docker/daemon.json 配置文件,若不存在,可新建
{
  "registry-mirrors": [
	"https://mirrors.ustc.edu.cn/",
    "https://hub-mirror.c.163.com",
    "https://mirror.baidubce.com"
  ]
}
  1. 重启 Docker 服务
$ sudo systemctl daemon-reload 
$ sudo systemctl restart docker
  1. 检查设置是否生效
$ sudo docker info
#结果中显示了我们设置的镜像服务器地址,则说明设置已经生效,返回的信息类似下面这样:
Registry Mirrors:
 https://hub-mirror.c.163.com/

2.2 拉取镜像

2.3 查看本地镜像

$ docker images
$ docker image ls

####返回参数解释
# REPOSITORY :镜像名称
# TAG        :镜像标签(版本)
# IMAGE ID   :镜像ID
# CREATED    :创建时间
# SIZE       : 镜像大小

2.4 启动镜像

$ docker run 镜像名:tag
$ docker run 镜像ID

$ docker run -it 37b81722dadc /bin/bash

$ docker run -d -p 90:80 nginx 

# -it是-i和-t的合并,表示通过交互式启动进入容器内部进行操作
# /bin/bash 表示启动的容器基于bash命令行进行操作
# 8cd9c9935d2a 为启动镜像后生成的容器id,每个镜像启动后都会有相应的容器
# 容器用来将镜像内部的环境和外部进行隔离,因此我们可以同时启动多个镜像,而相互之间不受影响
# 在容器中输入exit即可退出容器
Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Create and run a new container from an image

Aliases:
  docker container run, docker run

Options:
      --add-host list                    Add a custom host-to-IP mapping (host:ip)
      --annotation map                   Add an annotation to the container (passed through to the OCI runtime)
                                         (default map[])
  -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-interval duration   Time between running the check during the start period (ms|s|m|h)
                                         (default 0s)
      --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")
  -q, --quiet                            Suppress the pull output
      --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 the container
      --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.5 删除镜像

docker rmi -f 镜像id # 删除指定镜像, -f表示强制删除
docker rmi -f 镜像id 镜像id 镜像id # 同时删除多个镜像
# 骚操作,linux下有效
docker rmi -f $(docker images -aq) # 全部删除
$ docker start 容器id   # 启动容器
$ docker restart 容器id # 重启容器
$ docker stop 容器id    # 停止当前正在运行的容器
$ docker kill 容器id    # 强制停止当前容器

2.6 DIY镜像

$ docker commit -m="描述信息" -a="作者" 容器id 目标镜像名:[tag]

2.7 保存镜像到本地

$ docker save -o xxx.tar 镜像id

3、容器

3.1 查看容器

Usage:  docker ps [OPTIONS]

List containers

Aliases:
  docker container ls, docker container list, docker container ps, docker ps

Options:
  -a, --all             Show all containers (default shows just running) #显示所有容器,默认只显示运行中的容器
  -f, --filter filter   Filter output based on conditions provided#根据提供的条件,过滤输出内容
      --format string   Format output using a custom template:
                        'table':            Print output in table format with column headers (default)
                        'table TEMPLATE':   Print output in table format using the given Go template
                        'json':             Print in JSON format
                        'TEMPLATE':         Print output using the given Go template.
                        Refer to https://docs.docker.com/go/formatting/ for more information about formatting output with templates
  -n, --last int        Show n last created containers (includes all states) (default -1)#展示最近创建的n个容器(包括所有状态)
  -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

C:\Users\lynnh>docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

C:\Users\lynnh>docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
8cd9c9935d2a        37b81722dadc        "/bin/bash"         14 minutes ago      Exited (0) 9 minutes ago                       jolly_jennings
45ab1548e84f        hello-world         "/hello"            3 hours ago         Exited (0) 3 hours ago                         agitated_almeida

C:\Users\lynnh>docker ps -aq
8cd9c9935d2a
45ab1548e84f

3.2 启动和停止容器

docker start 容器id   # 启动容器
docker restart 容器id # 重启容器
docker stop 容器id    # 停止当前正在运行的容器
docker kill 容器id    # 强制停止当前容器

3.3 进入容器

$ docker exec -it 容器id /bin/bash
$ docker attach 容器id

# 区别
# docker exec   # 进入容器后开启一个新的终端,可以在里面操作(常用)
# docker attach # 进入容器正在执行的终端,不会开启新的终端

3.4 退出容器

exit     # 直接停止容器并退出
ctrl+p+q # 不停止容器,只退出,在linux下有效

3.5 删除容器

$ docker rm 容器id                    # 删除指定容器,不能删除正在运行的容器,可用 rm -f 强制删除
# 骚操作,linux下有效
$ docker rm -f $(docker ps -aq)      # 删除所有容器
$ docker ps -a -q|xargs docker rm -f # 删除所有容器

4、Docker file

4.1 docker build

Start a build

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

Start a build

Aliases:
  docker buildx build, docker buildx b

Options:
      --add-host strings              Add a custom host-to-IP mapping (format: "host:ip")
      --allow strings                 Allow extra privileged entitlement (e.g., "network.host",
                                      "security.insecure")
      --annotation stringArray        Add annotation to the image
      --attest stringArray            Attestation parameters (format: "type=sbom,generator=image")
      --build-arg stringArray         Set build-time variables
      --build-context stringArray     Additional build contexts (e.g., name=path)
      --builder string                Override the configured builder instance (default "default")
      --cache-from stringArray        External cache sources (e.g., "user/app:cache",
                                      "type=local,src=path/to/dir")
      --cache-to stringArray          Cache export destinations (e.g., "user/app:cache",
                                      "type=local,dest=path/to/dir")
      --cgroup-parent string          Set the parent cgroup for the "RUN" instructions during build
  -f, --file string                   Name of the Dockerfile (default: "PATH/Dockerfile")
      --iidfile string                Write the image ID to a file
      --label stringArray             Set metadata for an image
      --load                          Shorthand for "--output=type=docker"
      --metadata-file string          Write build result metadata to a file
      --network string                Set the networking mode for the "RUN" instructions during
                                      build (default "default")
      --no-cache                      Do not use cache when building the image
      --no-cache-filter stringArray   Do not cache specified stages
  -o, --output stringArray            Output destination (format: "type=local,dest=path")
      --platform stringArray          Set target platform for build
      --progress string               Set type of progress output ("auto", "plain", "tty"). Use
                                      plain to show container output (default "auto")
      --provenance string             Shorthand for "--attest=type=provenance"
      --pull                          Always attempt to pull all referenced images
      --push                          Shorthand for "--output=type=registry"
  -q, --quiet                         Suppress the build output and print image ID on success
      --sbom string                   Shorthand for "--attest=type=sbom"
      --secret stringArray            Secret to expose to the build (format:
                                      "id=mysecret[,src=/local/secret]")
      --shm-size bytes                Shared memory size for build containers
      --ssh stringArray               SSH agent socket or keys to expose to the build (format:
                                      "default|<id>[=<socket>|<key>[,<key>]]")
  -t, --tag stringArray               Name and optionally a tag (format: "name:tag")
      --target string                 Set the target build stage to build
      --ulimit ulimit                 Ulimit options (default [])

Experimental commands and flags are hidden. Set BUILDX_EXPERIMENTAL=1 to show them.
#常用命令示例
$ docker build -t 镜像名:版本号 .
#-t 指定镜像名称
#. 指定dockerfile文件位置为当前目录

4.2 Dockerfile

指令描述
FROM# 基础镜像,一切从这里开始构建
MAINTAINER镜像是谁写的,姓名+邮箱
RUN镜像构建的时候需要运行的命令
ADD添加内容: 比如加一个tomcat压缩包
WORKDIR镜像的工作目录
VOLUME镜像挂载的目录
EXPOSE保留暴露的端口
CMD指定这个容器启动的时候要运行的命令,只有最后一个会生效,可以被代替
ENTRYPOINT指定这个容器启动的时候需要运行的命令,可以追加命令
ONBUILD当构建一个被继承DockerFile 的时候就会运行 ONBUILD 的指令。触发指令
COPY类似ADD ,将我们的文件拷贝到镜像中
ENV构建的时候设置环境变量

etc:

From 172.16.208.16/base/centos7-java8-apm
ADD ./target/app.jar  /data/server/
ADD ./run.sh /data/server/

5、 其他docker命令

5.1 docker inspect

Usage:  docker inspect [OPTIONS] NAME|ID [NAME|ID...]

Return low-level information on Docker objects

Options:
  -f, --format string   Format output using a custom template:
                        'json':             Print in JSON format
                        'TEMPLATE':         Print output using the given Go template.
                        Refer to https://docs.docker.com/go/formatting/ for more information
                        about formatting output with templates
  -s, --size            Display total file sizes if the type is container
      --type string     Return JSON for specified type

5.2 docker logs

Usage:  docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

Aliases:
  docker container logs, docker logs

Options:
      --details        Show extra details provided to logs
  -f, --follow         Follow log output
      --since string   Show logs since timestamp (e.g. "2013-01-02T13:23:37Z") or relative
                       (e.g. "42m" for 42 minutes)
  -n, --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps
      --until string   Show logs before a timestamp (e.g. "2013-01-02T13:23:37Z") or relative
                       (e.g. "42m" for 42 minutes)

5.3 docker compose

文档信息

Search

    Table of Contents