【云原生】Docker学习笔记

2024-01-08 12:26:37

安装docker

系统信息:

passnight@passnight-s600:/etc/apt/trusted.gpg.d$ cat /etc/os-release 
PRETTY_NAME="Ubuntu 22.04.1 LTS"
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.1 LTS (Jammy Jellyfish)"
VERSION_CODENAME=jammy
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=jammy
sudo apt-get -y install apt-transport-https ca-certificates curl software-properties-common
# step 2: 安装GPG证书 
curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/alimirror-docker.gpg
# Step 3: 写入软件源信息
sudo add-apt-repository "deb [arch=amd64] https://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable"
sudo apt install docker-ce

# 验证是否安装成功
sudo docker version

运行hello world

passnight@passnight-s600:~$ sudo docker run hello-world

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

查看相关信息

# 查看hello world 镜像状态
passnight@passnight-s600:~$ sudo docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
hello-world   latest    feb5d9fea6a5   14 months ago   13.3kB

配置docker镜像

sudo vim /etc/docker/daemon.json
{
  "registry-mirrors": ["https://XXXXX.mirror.aliyuncs.com"]
}
:wq

docker常用命令

帮助命令

docker version # 查看版本
docker info # 查看信息
docker cmd --help # 帮助命令

镜像命令

docker images

# 功能:查看本地主机上的镜像
Usage:  docker images [OPTIONS] [REPOSITORY[:TAG]]

List images

Options:
  -a, --all             Show all images (default hides intermediate images)
      --digests         Show digests
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print images using a Go template
      --no-trunc        Don't truncate output
  -q, --quiet           Only show image IDs
  
# docker images -q
passnight@passnight-s600:~$ sudo docker images -aq
3e12e2ceb68f
3218b38490ce
feb5d9fea6a5

# docker images
# 1. repository: 仓库源
# 2. tag:标签
# 3. image id:id
# 4. created:创建时间
# 5. size大小
passnight@passnight-s600:~$ sudo docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
hello-world   latest    feb5d9fea6a5   14 months ago   13.3kB

docker search

passnight@passnight-s600:~$ docker search --help

Usage:  docker search [OPTIONS] TERM

Search the Docker Hub for images

Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print search using a Go template
      --limit int       Max number of search results (default 25)
      --no-trunc        Don't truncate output
# docker search mysql
passnight@passnight-s600:~$ sudo docker search mysql
NAME                            DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                           MySQL is a widely used, open-source relation…   13570     [OK]       
mariadb                         MariaDB Server is a high performing open sou…   5172      [OK]       
phpmyadmin                      phpMyAdmin - A web interface for MySQL and M…   700       [OK]       
percona                         Percona Server is a fork of the MySQL relati…   596       [OK]       
bitnami/mysql                   Bitnami MySQL Docker Image                      79                   [OK]
databack/mysql-backup           Back up mysql databases to... anywhere!         76                   
linuxserver/mysql-workbench                                                     45                   
ubuntu/mysql                    MySQL open source fast, stable, multi-thread…   38                   
linuxserver/mysql               A Mysql container, brought to you by LinuxSe…   38                   
circleci/mysql                  MySQL is a widely used, open-source relation…   28                   
google/mysql                    MySQL server for Google Compute Engine          22                   [OK]
rapidfort/mysql                 RapidFort optimized, hardened image for MySQL   13                   
bitnami/mysqld-exporter                                                         4                    
ibmcom/mysql-s390x              Docker image for mysql-s390x                    2                    
vitess/mysqlctld                vitess/mysqlctld                                1                    [OK]
newrelic/mysql-plugin           New Relic Plugin for monitoring MySQL databa…   1                    [OK]
hashicorp/mysql-portworx-demo                                                   0                    
rapidfort/mysql-official        RapidFort optimized, hardened image for MySQ…   0                    
docksal/mysql                   MySQL service images for Docksal - https://d…   0                    
mirantis/mysql                                                                  0                    
rapidfort/mysql8-ib             RapidFort optimized, hardened image for MySQ…   0                    
cimg/mysql                                                                      0                    
drud/mysql                                                                      0                    
silintl/mysql-backup-restore    Simple docker image to perform mysql backups…   0                    [OK]
corpusops/mysql                 https://github.com/corpusops/docker-images/     0 

# docker search mysql --filter=stars=5000

passnight@passnight-s600:~$ sudo docker search mysql --filter=stars=5000
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   13570     [OK]       
mariadb   MariaDB Server is a high performing open sou…   5172      [OK]

docker pull

passnight@passnight-s600:~$ docker pull --help

Usage:  docker 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
  
 # docer pull mysql
 # <=> docker pull mysql:latest
passnight@passnight-s600:~$ sudo docker pull mysql
Using default tag: latest # 默认tag
latest: Pulling from library/mysql
72a69066d2fe: Pull complete # 分层下载,联合文件系统
93619dbc5b36: Pull complete 
99da31dd6142: Pull complete 
626033c43d70: Pull complete 
37d5d7efb64e: Pull complete 
ac563158d721: Pull complete 
d2ba16033dad: Pull complete 
688ba7d5c01a: Pull complete 
00e060b6d11d: Pull complete 
1c04857f594f: Pull complete 
4d7cfa90e6ea: Pull complete 
e0431212d27d: Pull complete 
Digest: sha256:e9027fe4d91c0153429607251656806cc784e914937271037f7738bd5b8e7709 # 签名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest # 真实地址

 # docer pull mysql:5.7
passnight@passnight-s600:~$ sudo docker pull mysql:5.7
5.7: Pulling from library/mysql
72a69066d2fe: Already exists # 联合文件系统,与mysql:latest共用
93619dbc5b36: Already exists 
99da31dd6142: Already exists 
626033c43d70: Already exists 
37d5d7efb64e: Already exists 
ac563158d721: Already exists 
d2ba16033dad: Already exists 
0ceb82207cd7: Pull complete 
37f2405cae96: Pull complete 
e2482e017e53: Pull complete 
70deed891d42: Pull complete 
Digest: sha256:f2ad209efe9c67104167fc609cca6973c8422939491c9345270175a300419f94
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

docker rmi

passnight@passnight-s600:~$ docker rmi --help

Usage:  docker rmi [OPTIONS] IMAGE [IMAGE...]

Remove one or more images

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


passnight@passnight-s600:~$ docker rm --help

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

Remove one or more containers

Options:
  -f, --force     Force the removal of a running container (uses SIGKILL)
  -l, --link      Remove the specified link
  -v, --volumes   Remove anonymous volumes associated with the container

容器命令

docker run

passnight@passnight-s600:~$ sudo docker pull centos
Using default tag: latest
latest: Pulling from library/centos
a1d0c7532777: Pull complete 
Digest: sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177
Status: Downloaded newer image for centos:latest
docker.io/library/centos:latest

passnight@passnight-s600:~$ 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
# 常用run参数
--name="name": 容器名字
-d: 后台运行容器
-it: 使用交互方式运行
-p: 端口映射,主机端口:容器端口
-P: 随机指定端口

# 启动并进入容器
passnight@passnight-s600:~$ sudo docker run -it centos
[root@55e73b0c0b2e /]# 
# 退出容器
passnight@passnight-s600:~$ sudo docker run -it centos
[root@f1301eca1cf0 /]# exit
exit

# 后台运行某程序, notice: 必须有前台进程,否则容器docker会停止该容器
passnight@passnight-s600:~$ sudo docker run -d centos
b46065fdd55e69e5bfc409963d1e3796bb3855b8d0b863734990d3967b4d726a
passnight@passnight-s600:~$ sudo docker ps 
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

docker ps

passnight@passnight-s600:~$ docker ps --help

Usage:  docker ps [OPTIONS]

List containers

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
  
# docker ps: 查看正在运行的容器
passnight@passnight-s600:~$ sudo docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

# docker ps -a: 查看所有运行过的容器
passnight@passnight-s600:~$ sudo docker ps -a
CONTAINER ID   IMAGE         COMMAND       CREATED             STATUS                         PORTS     NAMES
f1301eca1cf0   centos        "/bin/bash"   2 minutes ago       Exited (0) 2 minutes ago                 interesting_clarke
55e73b0c0b2e   centos        "/bin/bash"   5 minutes ago       Exited (127) 3 minutes ago               zen_tesla

# docker ps -a -n: 查看n个运行过的容器
passnight@passnight-s600:~$ sudo docker ps -a -n=1
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                     PORTS     NAMES
f1301eca1cf0   centos    "/bin/bash"   3 minutes ago   Exited (0) 3 minutes ago             interesting_clarke

# docker ps -q 只显示id
passnight@passnight-s600:~$ sudo docker ps -aq
f1301eca1cf0
55e73b0c0b2e

退出容器

# exit: 容器停止并退出
passnight@passnight-s600:~$ sudo docker run -it centos
[root@4bbb0f5e8ccd /]# exit
exit
passnight@passnight-s600:~$ sudo docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

# ctrl p q: 退出容器,但不停止容器
[root@87fef132ad2e /]# passnight@passnight-s600:~$ 
passnight@passnight-s600:~$ sudo docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
87fef132ad2e   centos    "/bin/bash"   13 seconds ago   Up 12 seconds             peaceful_chaplygin

docker rm

passnight@passnight-s600:~$ docker rm --help

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

Remove one or more containers

Options:
  -f, --force     Force the removal of a running container (uses SIGKILL)
  -l, --link      Remove the specified link
  -v, --volumes   Remove anonymous volumes associated with the container

容器的基本操作 docker start, docker stop

docker start # 启动容器
passnight@passnight-s600:~$ sudo docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
passnight@passnight-s600:~$ sudo docker start 87fef132ad2e
87fef132ad2e
passnight@passnight-s600:~$ sudo docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
87fef132ad2e   centos    "/bin/bash"   4 minutes ago   Up 3 seconds             peaceful_chaplygin

# docker stop # 停止容器
passnight@passnight-s600:~$ sudo docker ps 
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
87fef132ad2e   centos    "/bin/bash"   3 minutes ago   Up 3 minutes             peaceful_chaplygin
passnight@passnight-s600:~$ sudo docker stop 87fef132ad2e
87fef132ad2e
passnight@passnight-s600:~$ sudo docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

其他命令

docker logs

passnight@passnight-s600:~$ docker logs --help

Usage:  docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

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)
      
# 查看centos的日志, 带时间,的最后三条日志
passnight@passnight-s600:~$ sudo docker logs -ft --tail=3 87fef132ad2e
2022-12-08T14:42:29.544494506Z [root@87fef132ad2e /]# exit
2022-12-08T14:45:02.220650206Z [root@87fef132ad2e /]# exit

docker top

passnight@passnight-s600:~$ docker top --help

Usage:  docker top CONTAINER [ps OPTIONS]

Display the running processes of a container

# 查看 centos 镜像信息
passnight@passnight-s600:~$ sudo docker top 1ca021eaf8f3
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                1700454             1700433             0                   22:56               pts/0               00:00:00            /bin/bash

docker imspect

passnight@passnight-s600:~$ docker inspect --help

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

Return low-level information on Docker objects

Options:
  -f, --format string   Format the output using the given Go template
  -s, --size            Display total file sizes if the type is container
      --type string     Return JSON for specified type

passnight@passnight-s600:~$ sudo docker inspect centos
# centos 的元数据
passnight@passnight-s600:~$ sudo docker inspect centos
[
    {
        "Id": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
        "RepoTags": [
            "centos:latest"
        ],
        "RepoDigests": [
            "centos@sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177"
        ],
.......................

docker exec

# 打开容器终端
passnight@passnight-s600:~$ docker exec --help

Usage:  docker 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
  
# docke exect 
passnight@passnight-s600:~$ sudo docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED        STATUS        PORTS     NAMES
1ca021eaf8f3   centos    "/bin/bash"   24 hours ago   Up 24 hours             zen_leavitt
passnight@passnight-s600:~$ sudo docker exec -it 1ca021eaf8f3 bash
[root@1ca021eaf8f3 /]#

docker attatch

# 进入正在运行的容器
passnight@passnight-s600:~$ docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
7c664221620d   centos    "/bin/bash"   4 seconds ago   Up 4 seconds             cranky_neumann
passnight@passnight-s600:~$ docker attach 7c664221620d
[root@7c664221620d /]#

docker cp

# docker cp container:path host:path
# 将容器中的命令拷贝到宿主机
passnight@passnight-s600:~/tmp$ docker attach db8e5869ea9c
[root@db8e5869ea9c /]# touch file	# 创建文件
[root@db8e5869ea9c /]# read escape sequence # Ctrl p q
passnight@passnight-s600:~/tmp$ docker cp db8e5869ea9c:/file ~/tmp #将文件拷贝出
passnight@passnight-s600:~/tmp$ ls
file

创建镜像

passnight@passnight-s600:~$ docker commit -h
Flag shorthand -h has been deprecated, please use --help

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

Create a new image from a container's changes

Options:
  -a, --author string    Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")
  -c, --change list      Apply Dockerfile instruction to the created image
  -m, --message string   Commit message
  -p, --pause            Pause container during commit (default true)

# docker exec -it tomcat1 bash, and modify the container
# -a=author, -m="message" container repository
passnight@passnight-s600:~$ docker commit -a="passnight" -m="cp webapps.dist to webapp" 4ddcf5cc9f0d tomcat2:1.0
sha256:99770909ed6b04d8c3c7494b817e5edb87f4be55760968366eaa253f2bd51440
passnight@passnight-s600:~$ docker images
REPOSITORY            TAG       IMAGE ID       CREATED          SIZE
tomcat2               1.0       99770909ed6b   45 seconds ago   684MB
tomcat                latest    fb5657adc892   11 months ago    680MB

容器数据卷

在这里插入图片描述

数据卷的使用

# 挂载卷
passnight@passnight-s600:~/docker$ docker run -it --name="centos2" -v ~/docker/centos2:/home centos bash
[root@606f7f66ebbd /]#
# 通过inspect 命令查看挂载情况
passnight@passnight-s600:~/docker/centos2$ docker inspect centos2 | grep -A 9 Mounts
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/home/passnight/docker/centos2",
                "Destination": "/home",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],
# 测试同步
[root@606f7f66ebbd home]# touch generateAFileInDocker # in docker
passnight@passnight-s600:~/docker/centos2$ ls
generateAFileInDocker
passnight@passnight-s600:~/docker/centos2$ sudo touch generateAFileInHost
[root@606f7f66ebbd home]# ls
generateAFileInDocker  generateAFileInHost

匿名挂载和具名挂载

# 创建镜像时匿名挂载
passnight@passnight-s600:~$ docker run -d --name nginx2 -v /etc/nginx nginx
b665c582b1cf5d95ab314b7bc7ac14470ad220fd12180eb1c57284471e51bc61
# 查看所有卷
passnight@passnight-s600:~$ docker volume ls
DRIVER    VOLUME NAME
local     1ac5e61b421164b556493a5093303c44adae878dc9cf13bdeec0e328b2b716da
local     6f9d838099c22ff9a0ce5d84e74a389002060801b9d4a6055a5ff650026159ed
local     541f0f10a15308ed94ac98964dcb65b12381d9f52a1442f5d373ab5b31c59fd0

# 具名挂载
passnight@passnight-s600:~$ docker run -d --name nginx3 -v named-ngnix:/etc/nginx nginx
63ce141c6cd5af4d29275b6fcc19b058e142bffc36b56474637eace9c24053de
passnight@passnight-s600:~$ docker volume ls
DRIVER    VOLUME NAME
local     1ac5e61b421164b556493a5093303c44adae878dc9cf13bdeec0e328b2b716da
local     6f9d838099c22ff9a0ce5d84e74a389002060801b9d4a6055a5ff650026159ed
local     541f0f10a15308ed94ac98964dcb65b12381d9f52a1442f5d373ab5b31c59fd0
local     named-ngnix

# 查看挂载位置
passnight@passnight-s600:~$ docker volume inspect named-ngnix
[
    {
        "CreatedAt": "2022-12-12T21:19:41+08:00",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/named-ngnix/_data",
        "Name": "named-ngnix",
        "Options": null,
        "Scope": "local"
    }
]
passnight@passnight-s600:~$ sudo ls /var/lib/docker/volumes
1ac5e61b421164b556493a5093303c44adae878dc9cf13bdeec0e328b2b716da  backingFsBlockDev
541f0f10a15308ed94ac98964dcb65b12381d9f52a1442f5d373ab5b31c59fd0  metadata.db
6f9d838099c22ff9a0ce5d84e74a389002060801b9d4a6055a5ff650026159ed  named-ngnix
passnight@passnight-s600:~$ sudo ls /var/lib/docker/volumes/named-ngnix/_data
conf.d  fastcgi_params  mime.types  modules  nginx.conf  scgi_params  uwsgi_params

总结:

  1. -v 容器内路径: 匿名挂载
  2. -v 卷名:容器内路径: 具名挂载
  3. -v /宿主机路径:容器内路径: 指定路径挂载
  4. -v ::access: 权限, ro为readonly, rw为readwrite

容器间数据卷绑定

passnight@passnight-s600:~/project/note/alg$ docker attach pcentos1
[root@857742a3c700 /]# cd volume01
[root@857742a3c700 volume01]# ls
[root@857742a3c700 volume01]# touch afile

# 使用--volume-from参数挂载
passnight@passnight-s600:~/project/note/alg$ docker run -it --name pcentos2 --volumes-from pcentos1 passnight/centos
[root@06ae5d9650e6 /]# ls /volume01
afile

实战

docker 安装nginx

# 1. 搜索镜像
passnight@passnight-s600:~$ docker search nginx
NAME                                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
nginx                                             Official build of Nginx.                        17798     [OK]
linuxserver/nginx                                 An Nginx container, brought to you by LinuxS…   182
bitnami/nginx                                     Bitnami nginx Docker Image                      148                  [OK]
ubuntu/nginx                                      Nginx, a high-performance reverse proxy & we…   70
bitnami/nginx-ingress-controller                  Bitnami Docker Image for NGINX Ingress Contr…   22                   [OK]
rancher/nginx-ingress-controller                                                                  11
kasmweb/nginx                                     An Nginx image based off nginx:alpine and in…   4

# 2. 拉取镜像
passnight@passnight-s600:~$ docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
a2abf6c4d29d: Already exists
a9edb18cadd1: Pull complete
589b7251471a: Pull complete
186b1aaa4aa6: Pull complete
b4df32aa5a72: Pull complete
a0bcbecc962e: Pull complete
Digest: sha256:0d17b565c37bcbd895e9d92315a05c1c3c9a29f762b011a10c54a66cd53c9b31
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest

# 3. 启动镜像
passnight@passnight-s600:~$ curl localhost:8848
# 未启动,无法连接
curl: (7) Failed to connect to localhost port 8848 after 0 ms: Connection refused

# 启动后
passnight@passnight-s600:~$ docker run -d --name nginx1 -p 8848:80 nginx
passnight@passnight-s600:~$ curl localhost:8848
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

docker 安装 tomcat

passnight@passnight-s600:~$ docker pull tomcat
passnight@passnight-s600:~$ docker run -d -p 8849:8080 --name tomcat1 tomcat
passnight@passnight-s600:~$ curl localhost:8849
<!doctype html><html lang="en"><head><title>HTTP Status 404 – Not Found</title><style type="text/css">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 404 – Not Found</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Description</b> The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.</p><hr class="line" /><h3>Apache Tomcat/10.0.14</h3></body></html>passnight@passnight-s600:~$

docker 安装 protainer

passnight@passnight-s600:~$ docker run -d -p 9000:9000 --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer

在这里插入图片描述

安装mysql并挂载数据

# 将配置/etc/mysql/conf.d配置文件绑定到本地/opt/docker/mysql1/etc/conf.d
# 将数据文件/var/lib/mysql 绑定到本地 /opt/docker/mysql/var/lib
# 配置环境变量:root 密码********
passnight@passnight-s600:~$ docker run -d -p 13306:3306 -v /opt/docker/mysql1/etc/conf.d:/etc/mysql/conf.d -v /opt/docker/mysql1/var/lib/mysql:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=******** --name="mysql1" mysql
76b30177b8d4cfc8f55c9cfe5a6a4e81c8c4eb58cbd698da02a285728fe36030

# 测试连接情况
passnight@passnight-s600:~$ mysql -u root -P 13306 -h localhost -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 42
Server version: 8.0.31-0ubuntu0.22.04.1 (Ubuntu)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

# 查看文件挂载情况,
# 注: passnight@passnight-s600:/opt/docker/mysql1$ sudo ln -s /opt/docker/mysql1/var/lib/mysql ./data
passnight@passnight-s600:/opt/docker/mysql1$ ls
data  etc  var

# 创建表,并观察文件
passnight@passnight-s600:/opt/docker/mysql1$ docker exec -it mysql1 bash
root@76b30177b8d4:/# mysql
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
root@76b30177b8d4:/# mysql -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 15
Server version: 8.0.27 MySQL Community Server - GPL

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create schema test;
Query OK, 1 row affected (0.00 sec)

passnight@passnight-s600:/opt/docker/mysql1/data$ ls
 auto.cnf        ca-key.pem       '#ib_16384_0.dblwr'   ib_logfile0     mysql                public_key.pem    test
 binlog.000001   ca.pem           '#ib_16384_1.dblwr'   ib_logfile1     mysql.ibd            server-cert.pem   undo_001
 binlog.000002   client-cert.pem   ib_buffer_pool       ibtmp1          performance_schema   server-key.pem    undo_002
 binlog.index    client-key.pem    ibdata1             '#innodb_temp'   private_key.pem      sys

制作tomcat镜像

下载tomcat和jdk压缩包

passnight@passnight-s600:~/tmp/tomcat-images$ wget https://download.java.net/java/GA/jmc8/05/binaries/jmc-8.3.0_linux-x64.tar.gz
passnight@passnight-s600:~/tmp/tomcat-images$ wget https://dlcdn.apache.org/tomcat/tomcat-9/v9.0.70/bin/apache-tomcat-9.0.70-fulldocs.tar.gz

编写Dockerfile

FROM centos

# 添加readme
COPY readme.md /usr/local/readme.md

# 添加环境
ADD jmc-8.3.0_linux-x64.tar.gz /usr/local
ADD apache-tomcat-9.0.70-fulldocs.tar.gz /usr/local

# 配置环境变量
ENV mypath /usr/local
ENV JAVA_HOME /usr/local/mc-8.3.0_linux-x64
ENV CLAPATH ${JAVA_HOME}/lib/dt.jar:${JAVA_HOME}/lib/tools.jar
ENV CATALINA_HOME /usr/local/tomcat-9.0-doc
ENV PATH=${PATH}:${JAVA_HOME}/bin:${CATALINA_HOME}/lib:${CATALINA_HOME}/bin

WORKDIR ${mypath}

EXPOSE 8080

RUN mkdir -p /usr/local/apache-tomcat-9.0.70/logs
RUN touch /usr/local/apache-tomcat-9.0.70/logs/catalina.log
CMD ${CATALINA_HOME}/bin/startup.sh && tail -F ${CATALINA_HOME}/logs/catalina.log

构建

passnight@passnight-s600:~/tmp/tomcat-images$ docker build -t ptomcat .
Sending build context to Docker daemon  105.5MB
Step 1/14 : FROM centos
 ---> 5d0da3dc9764
Step 2/14 : COPY readme.md /usr/local/readme.md
 ---> d77cdf7a405d
Step 3/14 : ADD jmc-8.3.0_linux-x64.tar.gz /usr/local
 ---> 376aeab6ac05
Step 4/14 : ADD apache-tomcat-9.0.70.tar.gz /usr/local
 ---> 8a8296fde5b8
Step 5/14 : ENV mypath /usr/local
 ---> Running in 801f07b2cad3
Removing intermediate container 801f07b2cad3
 ---> 99e88568f3a3
Step 6/14 : WORKDIR ${mypath}
 ---> Running in 1e10123983c1
Removing intermediate container 1e10123983c1
 ---> 5bd49688a821
Step 7/14 : ENV JAVA_HOME /usr/local/mc-8.3.0_linux-x64
 ---> Running in e8b5e96d4136
Removing intermediate container e8b5e96d4136
 ---> a02ed0e2f666
Step 8/14 : ENV CLAPATH ${JAVA_HOME}/lib/dt.jar:${JAVA_HOME}/lib/tools.jar
 ---> Running in bf40a48ebb64
Removing intermediate container bf40a48ebb64
 ---> 07c898719a13
Step 9/14 : ENV CATALINA_HOME /usr/local/apache-tomcat-9.0.70
 ---> Running in 53ef2fabcc3e
Removing intermediate container 53ef2fabcc3e
 ---> 38841ab2ebc5
Step 10/14 : ENV PATH=${PATH}:${JAVA_HOME}/bin:${CATALINA_HOME}/lib:${CATALINA_HOME}/bin
 ---> Running in 1801b6fed912
Removing intermediate container 1801b6fed912
 ---> b5af6af0e726
Step 11/14 : EXPOSE 8080
 ---> Running in 37b58f094b72
Removing intermediate container 37b58f094b72
 ---> 322a564963a4
Step 12/14 : RUN mkdir -p /usr/local/apache-tomcat-9.0.70/logs
 ---> Running in cb19c155b143
Removing intermediate container cb19c155b143
 ---> d7902879cc70
Step 13/14 : RUN touch /usr/local/apache-tomcat-9.0.70/logs/catalina.log
 ---> Running in b3d11b187313
Removing intermediate container b3d11b187313
 ---> 877c0a73e461
Step 14/14 : CMD ${CATALINA_HOME}/bin/startup.sh && tail -F ${CATALINA_HOME}/logs/catalina.log
 ---> Running in ef0c907c8a38
Removing intermediate container ef0c907c8a38
 ---> 5f4fcac39936
Successfully built 5f4fcac39936
Successfully tagged ptomcat:latest

# 启动镜像
passnight@passnight-s600:~/tmp/tomcat-images$ docker run -it ptomcat 
Using CATALINA_BASE:   /usr/local/apache-tomcat-9.0.70
Using CATALINA_HOME:   /usr/local/apache-tomcat-9.0.70
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-9.0.70/temp
Using JRE_HOME:        /usr/local/mc-8.3.0_linux-x64
Using CLASSPATH:       /usr/local/apache-tomcat-9.0.70/bin/bootstrap.jar:/usr/local/apache-tomcat-9.0.70/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.

docker部署mysql集群

启动主库

docker run -d -p 13306:3306 \
-v /opt/docker/mysql-master/etc/mysql/conf.d:/etc/mysql/conf.d \
-v /opt/docker/mysql-master/var/lib/mysql:/var/lib/mysql \
-v /opt/docker/mysql-master/var/log/mysql:/var/log/mysql \
-e MYSQL_ROOT_PASSWORD=******** \
--name="mysql-master" \
mysql

修改主库配置文件

## 设置server id
server_id=101
# 指定不需要同步的数据库名称
binlog-ignore-db=mysql
# 开启二进制日志功能
log-bin=mall-mysql-bin
# 设置二进制日志使用内存大小(事务)
binlog_cache_size=1M
# 设置使用的二进制日志格式(mixed, statement, row)
binlog_format=mixed
# 二进制日志过期清理时间
expire_logs_days=7
# 跳过主从复制中遇到的所有错误, 或指定类型的错误, 避免slave端复制终端
# 如 1062: 主键重复错误
slave_skip_errors=1062

创建从库用户

create user 'slave'@'%' identified by '********';
grant replication slave, replication client on *.* to 'slave'@'%';

创建从库

docker run -d -p 23306:3306 \
-v /opt/docker/mysql-slave/etc/mysql/conf.d:/etc/mysql/conf.d \
-v /opt/docker/mysql-slave/var/lib/mysql:/var/lib/mysql \
-v /opt/docker/mysql-slave/var/log/mysql:/var/log/mysql \
-e MYSQL_ROOT_PASSWORD=******** \
--name="mysql-slave" \
mysql
## 设置server id
server_id=102
# 指定不需要同步的数据库名称
binlog-ignore-db=mysql
# 开启二进制日志功能
log-bin=mall-mysql-bin
# 设置二进制日志使用内存大小(事务)
binlog_cache_size=1M
# 设置使用的二进制日志格式(mixed, statement, row)
binlog_format=mixed
# 二进制日志过期清理时间
expire_logs_days=7
# 跳过主从复制中遇到的所有错误, 或指定类型的错误, 避免slave端复制终端
# 如 1062: 主键重复错误
slave_skip_errors=1062

在这里插入图片描述

-- 主库
create user 'slave'@'%' IDENTIFIED WITH mysql_native_password BY '********';
grant replication slave, replication client on *.* to 'slave'@'%';
flush privileges;

-- 从库
change master to master_host ='server.passnight.local', master_password ='********', master_user ='slave',
    master_port =13306, master_log_file ='binlog.000004',master_log_pos =1175,master_connect_retry =30;

在这里插入图片描述

在这里插入图片描述

左主右从

DockerFile

初识

FROM centos

VOLUME [ "volume01", "volume02" ]

RUN echo "build complete"
RUN bash
passnight@passnight-s600:~/tmp$ docker build -f ./dockerfile -t passnight/centos .
Sending build context to Docker daemon   2.56kB
Step 1/4 : FROM centos
 ---> 5d0da3dc9764
Step 2/4 : VOLUME [ "volume01", "volume02" ]
 ---> Running in 3de03e6fa6a1
Removing intermediate container 3de03e6fa6a1
 ---> e08404a0d872
Step 3/4 : RUN echo "build complete"
 ---> Running in d3ea2bbacdcd
build complete
Removing intermediate container d3ea2bbacdcd
 ---> be7722093864
Step 4/4 : RUN bash
 ---> Running in 969bc3bd0094
Removing intermediate container 969bc3bd0094
 ---> 12b3b908f3d4
Successfully built 12b3b908f3d4

# 查看
passnight@passnight-s600:~/tmp$ docker images
REPOSITORY            TAG       IMAGE ID       CREATED         SIZE
passnight/centos      latest    12b3b908f3d4   2 minutes ago   231MB

# 查看目录
passnight@passnight-s600:~$ docker run -it passnight/centos bash
[root@b7206fd36f34 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var  volume01  volume02
  1. 所有关键字都是大写
  2. 使用#表示注释
  3. 每个指令都会创建并提交一个镜像层

常用指令

FROM # 基础镜像
MAINTAINER # 维护者信息, 姓名+邮箱
RUN # 运行命令
ADD # 添加镜像
WORKDIR # 镜像的工作目录
VOLUME # 挂载卷
EXPOSE # 暴露端口
CMD # 指定容器启动时运行的指令
ENTRYPOINT # 容器启动时运行指令,相比于CMD,CMD只有最后一个指令会生效
ONBUILD # 当构建一个被集成的DOCKERFILE, 就会运行ONBUILD指令
COPY # 将文件拷贝到镜像中
ENV # 设置环境变量

发布镜像

passnight@passnight-s600:~/tmp/tomcat-images$ docker push --help

Usage:  docker 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
  
# 登录
passnight@passnight-s600:~/tmp/tomcat-images$ docker login -u passnight
Password:
WARNING! Your password will be stored unencrypted in /home/passnight/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

# 发布
passnight@passnight-s600:~/tmp/tomcat-images$ docker tag ptomcat:latest passnight/tomcat:1.0
passnight@passnight-s600:~/tmp/tomcat-images$ docker push passnight/tomcat:1.0
The push refers to repository [docker.io/passnight/tomcat]
9a92e7215ef1: Pushed
bb4d83693a7b: Pushed
d58e910e09ae: Pushed
f17111f7ddc4: Pushed
74ddd0ec08fa: Pushed
1.0: digest: sha256:445c40c5e08582c23d86de1ccacb9e28addc2f2661bc8ae40712f58b5d8839b1 size: 1367

Docker compose

passnight@passnight-s600:~/shell$ docker-compose --help
Define and run multi-container applications with Docker.

Usage:
  docker-compose [-f <arg>...] [--profile <name>...] [options] [--] [COMMAND] [ARGS...]
  docker-compose -h|--help

Options:
  -f, --file FILE             Specify an alternate compose file
                              (default: docker-compose.yml)
  -p, --project-name NAME     Specify an alternate project name
                              (default: directory name)
  --profile NAME              Specify a profile to enable
  -c, --context NAME          Specify a context name
  --verbose                   Show more output
  --log-level LEVEL           Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  --ansi (never|always|auto)  Control when to print ANSI control characters
  --no-ansi                   Do not print ANSI control characters (DEPRECATED)
  -v, --version               Print version and exit
  -H, --host HOST             Daemon socket to connect to

  --tls                       Use TLS; implied by --tlsverify
  --tlscacert CA_PATH         Trust certs signed only by this CA
  --tlscert CLIENT_CERT_PATH  Path to TLS certificate file
  --tlskey TLS_KEY_PATH       Path to TLS key file
  --tlsverify                 Use TLS and verify the remote
  --skip-hostname-check       Don't check the daemon's hostname against the
                              name specified in the client certificate
  --project-directory PATH    Specify an alternate working directory
                              (default: the path of the Compose file)
  --compatibility             If set, Compose will attempt to convert keys
                              in v3 files to their non-Swarm equivalent (DEPRECATED)
  --env-file PATH             Specify an alternate environment file

Commands:
  build              Build or rebuild services
  config             Validate and view the Compose file
  create             Create services
  down               Stop and remove resources
  events             Receive real time events from containers
  exec               Execute a command in a running container
  help               Get help on a command
  images             List images
  kill               Kill containers
  logs               View output from containers
  pause              Pause services
  port               Print the public port for a port binding
  ps                 List containers
  pull               Pull service images
  push               Push service images
  restart            Restart services
  rm                 Remove stopped containers
  run                Run a one-off command
  scale              Set number of containers for a service
  start              Start services
  stop               Stop services
  top                Display the running processes
  unpause            Unpause services
  up                 Create and start containers
  version            Show version information and quit
version: '2'

services:
  config-server:
    image: springcommunity/spring-petclinic-config-server
    container_name: config-server
    mem_limit: 512M
    ports:
     - 8888:8888

  discovery-server:
    image: springcommunity/spring-petclinic-discovery-server
    container_name: discovery-server
    mem_limit: 512M
    depends_on:
      - config-server
    entrypoint: ["./dockerize","-wait=tcp://config-server:8888","-timeout=60s","--","java", "org.springframework.boot.loader.JarLauncher"]
    ports:
     - 8761:8761

  customers-service:
    image: springcommunity/spring-petclinic-customers-service
    container_name: customers-service
    mem_limit: 1024M
    depends_on:
     - config-server
     - discovery-server
    entrypoint: ["./dockerize","-wait=tcp://discovery-server:8761","-timeout=60s","--","java", "org.springframework.boot.loader.JarLauncher"]
    ports:
    - 8081:8081

  visits-service:
    image: springcommunity/spring-petclinic-visits-service
    container_name: visits-service
    mem_limit: 512M
    depends_on:
     - config-server
     - discovery-server
    entrypoint: ["./dockerize","-wait=tcp://discovery-server:8761","-timeout=60s","--","java", "org.springframework.boot.loader.JarLauncher"]
    ports:
     - 8082:8082

  vets-service:
    image: springcommunity/spring-petclinic-vets-service
    container_name: vets-service
    mem_limit: 512M
    depends_on:
     - config-server
     - discovery-server
    entrypoint: ["./dockerize","-wait=tcp://discovery-server:8761","-timeout=60s","--","java", "org.springframework.boot.loader.JarLauncher"]
    ports:
     - 8083:8083

  api-gateway:
    image: springcommunity/spring-petclinic-api-gateway
    container_name: api-gateway
    mem_limit: 1024M
    depends_on:
     - config-server
     - discovery-server
    entrypoint: ["./dockerize","-wait=tcp://discovery-server:8761","-timeout=60s","--","java", "org.springframework.boot.loader.JarLauncher"]
    ports:
     - 8080:8080

  tracing-server:
    image: openzipkin/zipkin
    container_name: tracing-server
    mem_limit: 512M
    environment:
    - JAVA_OPTS=-XX:+UnlockExperimentalVMOptions -Djava.security.egd=file:/dev/./urandom
    ports:
     - 9411:9411

  admin-server:
    image: springcommunity/spring-petclinic-admin-server
    container_name: admin-server
    mem_limit: 512M
    depends_on:
     - config-server
     - discovery-server
    entrypoint: ["./dockerize","-wait=tcp://discovery-server:8761","-timeout=60s","--","java", "org.springframework.boot.loader.JarLauncher"]
    ports:
     - 9090:9090

  ## Grafana / Prometheus

  grafana-server:
    build: ./docker/grafana
    container_name: grafana-server
    mem_limit: 256M
    ports:
    - 3000:3000

  prometheus-server:
    build: ./docker/prometheus
    container_name: prometheus-server
    mem_limit: 256M
    ports:
    - 9091:9090
    

# docker-compose up
passnight@passnight-s600:~/project/sample/spring-petclinic-microservices$ docker-compose ps
      Name                     Command                  State                             Ports                       
----------------------------------------------------------------------------------------------------------------------
admin-server        ./dockerize -wait=tcp://di ...   Up             0.0.0.0:9090->9090/tcp,:::9090->9090/tcp          
api-gateway         ./dockerize -wait=tcp://di ...   Up             0.0.0.0:8080->8080/tcp,:::8080->8080/tcp, 8081/tcp
config-server       java org.springframework.b ...   Up             0.0.0.0:8888->8888/tcp,:::8888->8888/tcp          
customers-service   ./dockerize -wait=tcp://di ...   Up             0.0.0.0:8081->8081/tcp,:::8081->8081/tcp          
discovery-server    ./dockerize -wait=tcp://co ...   Up             0.0.0.0:8761->8761/tcp,:::8761->8761/tcp          
grafana-server      /run.sh                          Up             0.0.0.0:3000->3000/tcp,:::3000->3000/tcp          
prometheus-server   /bin/prometheus --config.f ...   Up             0.0.0.0:9091->9090/tcp,:::9091->9090/tcp          
tracing-server      start-zipkin                     Up (healthy)   9410/tcp, 0.0.0.0:9411->9411/tcp,:::9411->9411/tcp
vets-service        ./dockerize -wait=tcp://di ...   Up             8081/tcp, 0.0.0.0:8083->8083/tcp,:::8083->8083/tcp
visits-service      ./dockerize -wait=tcp://di ...   Exit 1    
passnight@passnight-s600:~/project/sample/spring-petclinic-microservices$ docker-compose down
Stopping vets-service      ... done
Stopping customers-service ... done
Stopping api-gateway       ... done
Stopping admin-server      ... done
Stopping discovery-server  ... done
Stopping prometheus-server ... done
Stopping config-server     ... done
Stopping grafana-server    ... done
Stopping tracing-server    ... done
Removing visits-service    ... done
Removing vets-service      ... done
Removing customers-service ... done
Removing api-gateway       ... done
Removing admin-server      ... done
Removing discovery-server  ... done
Removing prometheus-server ... done
Removing config-server     ... done
Removing grafana-server    ... done
Removing tracing-server    ... done
passnight@passnight-s600:~/project/sample/spring-petclinic-microservices$ docker-compose ps
Name   Command   State   Ports
------------------------------

网络

Docker部署Prometheus

version: "3"
services:
  prometheus:
    container_name: prometheus
    image: prom/prometheus
    restart: always
    ports:
      - 9090:9090
    volumes:
      - /opt/docker/prometheus/data:/prometheus-data
      - /opt/docker/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
    networks:
      monitor:
       ipv4_address: 172.50.0.100
networks:
  monitor:
   ipam:
     driver: default
     config:
       - subnet: 172.50.0.0/16
         gateway: 172.50.0.1

Docker部署Pushgateway

version: "3"
services:
  pushgateway:
    container_name: pushgateway
    restart: always
    image: prom/pushgateway
    ports:
      - 9091:9091
    networks:
      prometheus_monitor:
       ipv4_address: 172.50.0.101
networks:
  prometheus_monitor:
    external: true

文章来源:https://blog.csdn.net/apple_50661801/article/details/135377069
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。