微服务day02

news2024/12/23 10:19:16

教学文档:

黑马教学文档

Docker

Docker的安装 

镜像和容器

命令解读

常见命令

案例

查看DockerHub,拉取Nginx镜像,创建并运行容器

搜索Nginx镜像:在 www.hub.docker.com 网站进行查询

拉取镜像:

docker pull nginx

查看本地镜像列表:

docker images

将拉取到本地的镜像进行打包,保存为文件

[root@server02 ~]# docker save --help

//查询docker save的命令的用法

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

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

Aliases:
  docker image save, docker save

//由此可知 该命令有 -o 表示设置 镜像的存储文件nginx.tar
Options:
  -o, --output string   Write to a file, instead of STDOUT
[root@server02 ~]# ^C
[root@server02 ~]# docker save -o nginx.tar nginx
[root@server02 ~]# ls
anaconda-ks.cfg  dist.zip  hello            install.sh                       nginx.tar        RDM-用户需求说明书.doc  公共  视频  文档  音乐
Desktop          download  hello-nginx.zip  jdk-17.0.8_linux-x64_bin.tar.gz  original-ks.cfg  xp-install.log          模板  图片  下载  桌面
[root@server02 ~]#

删除本地镜像

[root@server02 ~]# docker rmi nginx
Untagged: nginx:latest
Untagged: nginx@sha256:fad8e1cd52e24bce7b72cd7cb674a2efad671647b917055f5bd8a1f7ac9b1af8
Deleted: sha256:3f8a4339aadda5897b744682f5f774dc69991a81af8d715d37a616bb4c99edf5
Deleted: sha256:bb528503f6f01b70cd8de94372e1e3196fad3b28da2f69b105e95934263b0487
Deleted: sha256:410204d28a96d436e31842a740ad0c827f845d22e06f3b1ff19c3b22706c3ed4
Deleted: sha256:2ec5c0a4cb57c0af7c16ceda0b0a87a54f01f027ed33836a5669ca266cafe97a
[root@server02 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                   CREATED        STATUS          PORTS                                                  NAMES
d81b6044c59d   mysql     "docker-entrypoint.s…"   18 hours ago   Up 17 minutes   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   mysql
[root@server02 ~]#

提取本地镜像文件

[root@server02 ~]# docker load --help

Usage:  docker load [OPTIONS]

Load an image from a tar archive or STDIN

Aliases:
  docker image load, docker load

Options:
  -i, --input string   Read from tar archive file, instead of STDIN
  -q 表示是否显示提去细节
  -q, --quiet          Suppress the load output
[root@server02 ~]#

提去本地文件,只需要指定文件名即可

[root@server02 ~]# docker load -i nginx.tar
2ec5c0a4cb57: Loading layer [==================================================>]  58.43MB/58.43MB
73e2bd445514: Loading layer [==================================================>]  53.76MB/53.76MB
a103d141fc98: Loading layer [==================================================>]  3.584kB/3.584kB
Loaded image: nginx:latest
[root@server02 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                   CREATED        STATUS          PORTS                                                  NAMES
d81b6044c59d   mysql     "docker-entrypoint.s…"   19 hours ago   Up 23 minutes   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   mysql
[root@server02 ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
mysql        latest    be960704dfac   2 weeks ago   602MB
nginx        latest    3f8a4339aadd   6 years ago   108MB
[root@server02 ~]#

创建并运行NGINX容器


d81b6044c59d   mysql     "docker-entrypoint.s…"   20 hours ago   Up 2 hours   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   mysql
[root@server02 ~]# docker run -d --name nginx -p 90:80 nginx
cd42761dd7ead46aa2c0a9147f5fe0c1f9d200a253cfeee584d6b03d6c66a30b

查看容器

# 第5步,查看运行中容器
docker ps
# 也可以加格式化方式访问,格式会更加清爽
docker ps --format "table {{.ID}}\t{{.Image}}\t{{.Ports}}\t{{.Status}}\t{{.Names}}"

关闭进程

[root@server02 ~]# docker stop nginx
nginx
[root@server02 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED              STATUS                     PORTS                                                  NAMES
cd42761dd7ea   nginx     "nginx -g 'daemon of…"   About a minute ago   Exited (0) 4 seconds ago                                                          nginx
d81b6044c59d   mysql     "docker-entrypoint.s…"   20 hours ago         Up 2 hours                 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   mysql
[root@server02 ~]#

启动容器

[root@server02 ~]# docker start nginx
nginx
[root@server02 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED         STATUS        PORTS                                                  NAMES
cd42761dd7ea   nginx     "nginx -g 'daemon of…"   2 minutes ago   Up 1 second   0.0.0.0:90->80/tcp, :::90->80/tcp                      nginx
d81b6044c59d   mysql     "docker-entrypoint.s…"   20 hours ago    Up 2 hours    0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   mysql
[root@server02 ~]#

查看容器详细信息

# 第11步,查看容器详细信息
docker inspect nginx

进入容器



# 第12步,进入容器,查看容器内目录
-it 表示进入命令行交互
bash 为指定交互 语言
docker exec -it nginx bash
# 或者,可以进入MySQL
docker exec -it mysql mysql -uroot -p

删除容器

# 第13步,删除容器
docker rm nginx
# 发现无法删除,因为容器运行中,强制删除容器
docker rm -f nginx

[root@server02 ~]# docker rm nginx
Error response from daemon: cannot remove container "/nginx": container is running: stop the container before removing or force remove
[root@server02 ~]# docker rm -f nginx
nginx
[root@server02 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED        STATUS       PORTS                                                  NAMES
d81b6044c59d   mysql     "docker-entrypoint.s…"   20 hours ago   Up 2 hours   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   mysql
[root@server02 ~]#

命令别名

设置别名:root目录下 .bashrc文件进行设置

# .bashrc

# User specific aliases and functions

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi
~
~
~
~

修改文件,

# 修改/root/.bashrc文件
vi /root/.bashrc
内容如下:
# .bashrc

# User specific aliases and functions

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
alias dps='docker ps --format "table {{.ID}}\t{{.Image}}\t{{.Ports}}\t{{.Status}}\t{{.Names}}"'
alias dis='docker images'

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

执行命令使别名生效

source /root/.bashrc

实例:

[root@server02 ~]# vim .bashrc
[root@server02 ~]# source /root/.bashrc
[root@server02 ~]# dps
CONTAINER ID   IMAGE     PORTS                                                  STATUS       NAMES
d81b6044c59d   mysql     0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   Up 3 hours   mysql
[root@server02 ~]# dis
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
mysql        latest    be960704dfac   2 weeks ago   602MB
nginx        latest    3f8a4339aadd   6 years ago   108MB
[root@server02 ~]#

数据卷

案例:利用Nginx容器部署静态资源

  1. 进入容器内部:
[root@server02 ~]# docker exec -it nginx bash
  1. 通过在DockerHub中查找可知Nginx的静态资源存放在 ‘/usr/share/nginx/html/index.html’文件中,由于容器没有提供非必要的依赖,所以没有修改文件的命令(vim)无法修改,由此引入数据卷。
[root@server02 ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
mysql        latest    be960704dfac   2 weeks ago   602MB
nginx        latest    3f8a4339aadd   6 years ago   108MB
[root@server02 ~]# docker run -d --name nginx -p 90:80 nginx
4081207a48ee7f1338b2136166b72f1adb424f5482193ab2a52e9c747acd481d
[root@server02 ~]# docker exec -it nginx bash
root@4081207a48ee:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@4081207a48ee:/# cd /usr/share/nginx/html
root@4081207a48ee:/usr/share/nginx/html# ls
50x.html  index.html
root@4081207a48ee:/usr/share/nginx/html# vi index.html
bash: vi: command not found
root@4081207a48ee:/usr/share/nginx/html#

        

 

删除原有的Nginx的容器

[root@server02 ~]# docker rm -f nginx
nginx

创建新的容器并创建数据卷,设置数据卷名称为html,根据容器中的存储位置指定

[root@server02 ~]# docker run -d --name nginx -p 90:80 -v html:/usr/share/nginx/html nginx
c0f9d2c91c9dd88f2e767bda76453f0f836585c71b4dc129886850bc7a2fe130
[root@server02 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED         STATUS         PORTS                                                  NAMES
c0f9d2c91c9d   nginx     "nginx -g 'daemon of…"   8 seconds ago   Up 6 seconds   0.0.0.0:90->80/tcp, :::90->80/tcp                      nginx
d81b6044c59d   mysql     "docker-entrypoint.s…"   22 hours ago    Up 4 hours     0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   mysql
[root@server02 ~]# docker volume ps

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 unused local volumes
  rm          Remove one or more volumes
  update      Update a volume (cluster volumes only)

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

显示所有的数据卷

[root@server02 ~]# docker volume ls
DRIVER    VOLUME NAME
local     bb415299e39a1c7425861ee4add16668301e28c419cde8e35f5c436a69f228a4
local     html

展示数据卷的详情信息,其中有宿主机中文件的位置
[root@server02 ~]# docker volume inspect html

[
    {
        "CreatedAt": "2024-11-02T19:57:10+08:00",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/html/_data",
        "Name": "html",
        "Options": null,
        "Scope": "local"
    }
]
[root@server02 ~]# ^C

进入宿主机的文件位置
[root@server02 ~]# cd /var/lib/docker/volumes/html/_data
[root@server02 _data]# ls
50x.html  index.html
[root@server02 _data]# cat index.html

容器中的数据
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    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>
[root@server02 _data]#

案例2:Mysql数据挂载

查看Mysql容器的详细挂载:

# 1.查看MySQL容器详细信息
docker inspect mysql
# 关注其中.Config.Volumes部分和.Mounts部分

[root@server02 _data]# docker inspect mysql
[
    {
        "Id": "d81b6044c59d6dc6bdfd89ee6308b24c8b15bc62a67e58eb58a51471663fdb11",
        "Created": "2024-11-01T13:40:38.673884478Z",
        "Path": "docker-entrypoint.sh",
        "Args": [
            "mysqld"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 1988,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2024-11-02T12:43:18.287204296Z",
            "FinishedAt": "2024-11-02T12:42:46.40149356Z"
        },
        "Image": "sha256:be960704dfac8744a2e2df80c90087551a998ac008916b9d1423d7b0c5ee33ea",
        "ResolvConfPath": "/var/lib/docker/containers/d81b6044c59d6dc6bdfd89ee6308b24c8b15bc62a67e58eb58a51471663fdb11/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/d81b6044c59d6dc6bdfd89ee6308b24c8b15bc62a67e58eb58a51471663fdb11/hostname",
        "HostsPath": "/var/lib/docker/containers/d81b6044c59d6dc6bdfd89ee6308b24c8b15bc62a67e58eb58a51471663fdb11/hosts",
        "LogPath": "/var/lib/docker/containers/d81b6044c59d6dc6bdfd89ee6308b24c8b15bc62a67e58eb58a51471663fdb11/d81b6044c59d6dc6bdfd89ee6308b24c8b15bc62a67e58eb58a51471663fdb11-json.log",
        "Name": "/mysql",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "bridge",
            "PortBindings": {
                "3306/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "3306"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "always",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "ConsoleSize": [
                40,
                80
            ],
            "CapAdd": null,
            "CapDrop": null,
            "CgroupnsMode": "host",
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": [],
            "BlkioDeviceWriteBps": [],
            "BlkioDeviceReadIOps": [],
            "BlkioDeviceWriteIOps": [],
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": [],
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware",
                "/sys/devices/virtual/powercap"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/3cf60d95239daad11fb5ab3980198891888748066b529da9d663da08d9dbcf7f-init/diff:/var/lib/docker/overlay2/2e296e4d0a879890f34b553a9c3f59fa842faf33f37cdd692113dd269ec1adef/diff:/var/lib/docker/overlay2/2c31d039bb31ffb6ac4da3b76ee29ac8ee1b7b918c7be92595d9a76c63cbf0e0/diff:/var/lib/docker/overlay2/7a1225bf1b17ea29ec4595d8fb4b2b41e3a65f9f7ea532181bca4c259cc8df8d/diff:/var/lib/docker/overlay2/9c123ce4975933c8fdd1d01976c202afd48c4f7425e97ee29b363984c26898bb/diff:/var/lib/docker/overlay2/2e56e6f4d9796d51c25133bdf1f652254678c379a584edc4dd4340b1af1b6a36/diff:/var/lib/docker/overlay2/e8e715b5664a9962b35f9bbf33f62d814d7de58a29c11da00a2c9b41c9eb51da/diff:/var/lib/docker/overlay2/36f7c8ada99b2753cb094209970fa771f5d104b1e1c04a3234fea11260f5055c/diff:/var/lib/docker/overlay2/c4ddb63b3f27ffc789739b457035c23e6c7cd762e2a58da055a0f8ccb6c2e7f7/diff:/var/lib/docker/overlay2/66bc1e7635002279b4e9a3167244ac63845ac61f0bbf1e69ce7b2acfc2f45ee0/diff:/var/lib/docker/overlay2/fa8051a8bb240be1431a320cc952996f212a9a0282a8d2e31e15ad2817a6bc29/diff",
                "MergedDir": "/var/lib/docker/overlay2/3cf60d95239daad11fb5ab3980198891888748066b529da9d663da08d9dbcf7f/merged",
                "UpperDir": "/var/lib/docker/overlay2/3cf60d95239daad11fb5ab3980198891888748066b529da9d663da08d9dbcf7f/diff",
                "WorkDir": "/var/lib/docker/overlay2/3cf60d95239daad11fb5ab3980198891888748066b529da9d663da08d9dbcf7f/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [
            {
                "Type": "volume",
                "Name": "bb415299e39a1c7425861ee4add16668301e28c419cde8e35f5c436a69f228a4",
                "Source": "/var/lib/docker/volumes/bb415299e39a1c7425861ee4add16668301e28c419cde8e35f5c436a69f228a4/_data",
                "Destination": "/var/lib/mysql",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ],
        "Config": {
            "Hostname": "d81b6044c59d",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "3306/tcp": {},
                "33060/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "TZ=Asia/Shanghai",
                "MYSQL_ROOT_PASSWORD=123",
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "GOSU_VERSION=1.17",
                "MYSQL_MAJOR=innovation",
                "MYSQL_VERSION=9.1.0-1.el9",
                "MYSQL_SHELL_VERSION=9.1.0-1.el9"
            ],
            "Cmd": [
                "mysqld"
            ],
            "Image": "mysql",
            "Volumes": {
                "/var/lib/mysql": {}
            },
            "WorkingDir": "/",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "99e3029f08cd8edcaf9feac159a4a80a295b2751a97e3ab7f8ccd098ba3edfcd",
            "SandboxKey": "/var/run/docker/netns/99e3029f08cd",
            "Ports": {
                "3306/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "3306"
                    },
                    {
                        "HostIp": "::",
                        "HostPort": "3306"
                    }
                ],
                "33060/tcp": null
            },
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "bb696f63baf3dfc2a498766837c478b3e535bd0d07414b66db75af55f57438bb",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "MacAddress": "02:42:ac:11:00:02",
                    "NetworkID": "2479e9c603f8bd3f6a4815a430cfdc37081daa5fd57ad1a8225a92e309c7dd90",
                    "EndpointID": "bb696f63baf3dfc2a498766837c478b3e535bd0d07414b66db75af55f57438bb",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "DriverOpts": null,
                    "DNSNames": null
                }
            }
        }
    }
]
[root@server02 _data]#

Mounts部分为挂载信息,在创建容器时就自动创建挂载用来存储数据库中的数据。使用的是匿名卷,

可以发现,其中有几个关键属性:

  • Name:数据卷名称。由于定义容器未设置容器名,这里的就是匿名卷自动生成的名字,一串hash值。

  • Source:宿主机目录

  • Destination : 容器内的目录

上述配置是将容器内的/var/lib/mysql这个目录,与数据卷bb415299e39a1c7425861ee4add16668301e28c419cde8e35f5c436a69f228a4挂载。于是在宿主机中就有了/var/lib/docker/volumes/bb415299e39a1c7425861ee4add16668301e28c419cde8e35f5c436a69f228a4/_data这个目录。这就是匿名数据卷对应的目录,其使用方式与普通数据卷没有差别。

可以发现,数据卷的目录结构较深,如果我们去操作数据卷目录会不太方便。在很多情况下,我们会直接将容器目录与宿主机指定目录挂载。挂载语法与数据卷类似:

# 挂载本地目录
-v 本地目录:容器内目录
# 挂载本地文件
-v 本地文件:容器内文件

注意:本地目录或文件必须以 /./开头,如果直接以名字开头,会被识别为数据卷名而非本地目录名。

-v mysql:/var/lib/mysql # 会被识别为一个数据卷叫mysql,运行时会自动创建这个数据卷
-v ./mysql:/var/lib/mysql # 会被识别为当前目录下的mysql目录,运行时如果不存在会创建目录

创建要挂载的文件夹,并将提供的资料中的文件拉人文件夹中,包括配置文件和初始化数据库文件。

[root@server02 _data]# ^C
[root@server02 _data]# cd /root
[root@server02 ~]# mkdir mysql
[root@server02 ~]# cd mysql
[root@server02 mysql]# mkdir data
[root@server02 mysql]# mkdir init
[root@server02 mysql]# mkdir conf
[root@server02 mysql]# ls
conf  data  init
[root@server02 mysql]#

删除已存在的数据库容器:

[root@server02 mysql]# docker rm -f mysql
mysql
[root@server02 mysql]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED       STATUS          PORTS                               NAMES
c0f9d2c91c9d   nginx     "nginx -g 'daemon of…"   2 hours ago   Up 34 minutes   0.0.0.0:90->80/tcp, :::90->80/tcp   nginx
[root@server02 mysql]#

修改新的数据库容器的创建语句:

docker run -d \
  --name mysql \
  -p 3306:3306 \
  -e TZ=Asia/Shanghai \
  -e MYSQL_ROOT_PASSWORD=123 \
  -v ./mysql/data:/var/lib/mysql \
  -v ./mysql/conf:/etc/mysql/conf.d \
  -v ./mysql/init:/docker-entrypoint-initdb.d \
  mysql
# 4.查看root目录,可以发现~/mysql/data目录已经自动创建好了
ls -l mysql
# 结果:
总用量 4
drwxr-xr-x. 2 root    root   20 5月  19 15:11 conf
drwxr-xr-x. 7 polkitd root 4096 5月  19 15:11 data
drwxr-xr-x. 2 root    root   23 5月  19 15:11 init

# 查看data目录,会发现里面有大量数据库数据,说明数据库完成了初始化
ls -l data

# 5.查看MySQL容器内数据
# 5.1.进入MySQL
docker exec -it mysql mysql -uroot -p123
# 5.2.查看编码表
show variables like "%char%";
# 5.3.结果,发现编码是utf8mb4没有问题
+--------------------------+--------------------------------+
| Variable_name            | Value                          |
+--------------------------+--------------------------------+
| character_set_client     | utf8mb4                        |
| character_set_connection | utf8mb4                        |
| character_set_database   | utf8mb4                        |
| character_set_filesystem | binary                         |
| character_set_results    | utf8mb4                        |
| character_set_server     | utf8mb4                        |
| character_set_system     | utf8mb3                        |
| character_sets_dir       | /usr/share/mysql-8.0/charsets/ |
+--------------------------+--------------------------------+

# 6.查看数据
# 6.1.查看数据库
show databases;
# 结果,hmall是黑马商城数据库
+--------------------+
| Database           |
+--------------------+
| hmall              |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)
# 6.2.切换到hmall数据库
use hmall;
# 6.3.查看表
show tables;
# 结果:
+-----------------+
| Tables_in_hmall |
+-----------------+
| address         |
| cart            |
| item            |
| order           |
| order_detail    |
| order_logistics |
| pay_order       |
| user            |
+-----------------+
# 6.4.查看address表数据
+----+---------+----------+--------+----------+-------------+---------------+-----------+------------+-------+
| id | user_id | province | city   | town     | mobile      | street        | contact   | is_default | notes |
+----+---------+----------+--------+----------+-------------+---------------+-----------+------------+-------+
| 59 |       1 | 北京     | 北京   | 朝阳区    | 13900112222 | 金燕龙办公楼   | 李佳诚    | 0          | NULL  |
| 60 |       1 | 北京     | 北京   | 朝阳区    | 13700221122 | 修正大厦       | 李佳红    | 0          | NULL  |
| 61 |       1 | 上海     | 上海   | 浦东新区  | 13301212233 | 航头镇航头路   | 李佳星    | 1          | NULL  |
| 63 |       1 | 广东     | 佛山   | 永春      | 13301212233 | 永春武馆       | 李晓龙    | 0          | NULL  |
+----+---------+----------+--------+----------+-------------+---------------+-----------+------------+-------+
4 rows in set (0.00 sec)

自定义镜像

例如,要基于Ubuntu镜像来构建一个Java应用,其Dockerfile内容如下:

# 指定基础镜像
FROM ubuntu:16.04
# 配置环境变量,JDK的安装目录、容器内时区
ENV JAVA_DIR=/usr/local
ENV TZ=Asia/Shanghai
# 拷贝jdk和java项目的包
COPY ./jdk8.tar.gz $JAVA_DIR/
COPY ./docker-demo.jar /tmp/app.jar
# 设定时区
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
# 安装JDK
RUN cd $JAVA_DIR \
 && tar -xf ./jdk8.tar.gz \
 && mv ./jdk1.8.0_144 ./java8
# 配置环境变量
ENV JAVA_HOME=$JAVA_DIR/java8
ENV PATH=$PATH:$JAVA_HOME/bin
# 指定项目监听的端口
EXPOSE 8080
# 入口,java项目的启动命令
ENTRYPOINT ["java", "-jar", "/app.jar"]

就有人提供了基础的系统加JDK环境,我们在此基础上制作java镜像,就可以省去JDK的配置了:

# 基础镜像
FROM openjdk:11.0-jre-buster
# 设定时区
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
# 拷贝jar包
COPY docker-demo.jar /app.jar
# 入口
ENTRYPOINT ["java", "-jar", "/app.jar"]

由于要下载JDK到本地所以先上传JDK到本地镜像


[root@server02 ~]# docker load -i jdk.tar
2c7e7ab2260a: Loading layer [==================================================>]  119.3MB/119.3MB
9ad2165feb02: Loading layer [==================================================>]  17.18MB/17.18MB
92903c3857f8: Loading layer [==================================================>]  17.87MB/17.87MB
1736ab871b32: Loading layer [==================================================>]  12.18MB/12.18MB
6f8e4cb95a88: Loading layer [==================================================>]  3.584kB/3.584kB
41080a0c646f: Loading layer [==================================================>]  141.8MB/141.8MB
Loaded image: openjdk:11.0-jre-buster
[root@server02 ~]# docker ps -
"docker ps" accepts no arguments.
See 'docker ps --help'.

Usage:  docker ps [OPTIONS]

List containers
[root@server02 ~]# docker ps -A
unknown shorthand flag: 'A' in -A
See 'docker ps --help'.
[root@server02 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED             STATUS             PORTS                                                  NAMES
dbf730d0ef60   mysql     "docker-entrypoint.s…"   About an hour ago   Up About an hour   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   mysql
c0f9d2c91c9d   nginx     "nginx -g 'daemon of…"   3 hours ago         Up 2 hours         0.0.0.0:90->80/tcp, :::90->80/tcp                      nginx
[root@server02 ~]# docker images
REPOSITORY   TAG               IMAGE ID       CREATED       SIZE
mysql        latest            be960704dfac   2 weeks ago   602MB
openjdk      11.0-jre-buster   57925f2e4cff   2 years ago   301MB
nginx        latest            3f8a4339aadd   6 years ago   108MB
[root@server02 ~]# cd /root/demo
[root@server02 demo]# docker build -t docker-demo:1.0 .
[+] Building 1.0s (8/8) FINISHED                                                                                                               docker:default
 => [internal] load build definition from Dockerfile                                                                                                     0.0s
 => => transferring dockerfile: 299B                                                                                                                     0.0s
 => [internal] load metadata for docker.io/library/openjdk:11.0-jre-buster                                                                               0.0s
 => [internal] load .dockerignore                                                                                                                        0.0s
 => => transferring context: 2B                                                                                                                          0.0s
 => [1/3] FROM docker.io/library/openjdk:11.0-jre-buster                                                                                                 0.1s
 => [internal] load build context                                                                                                                        0.2s
 => => transferring context: 17.70MB                                                                                                                     0.2s
 => [2/3] RUN ln -snf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo Asia/Shanghai > /etc/timezone                                             0.6s
 => [3/3] COPY docker-demo.jar /app.jar                                                                                                                  0.1s
 => exporting to image                                                                                                                                   0.1s
 => => exporting layers                                                                                                                                  0.1s
 => => writing image sha256:9e95eddcf939bc4f47db257b48be435c1ef4fbe7f954155bb7ffd38c54ecb3f5                                                             0.0s
 => => naming to docker.io/library/docker-demo:1.0                                                                                                       0.0s
[root@server02 demo]# docker images
REPOSITORY    TAG               IMAGE ID       CREATED         SIZE
docker-demo   1.0               9e95eddcf939   5 seconds ago   319MB
mysql         latest            be960704dfac   2 weeks ago     602MB
openjdk       11.0-jre-buster   57925f2e4cff   2 years ago     301MB
nginx         latest            3f8a4339aadd   6 years ago     108MB
[root@server02 demo]# docker run -d --name dd -p 8080:8080 docker-demo:1.0
a8fd9609526f1f185148cd5e37bb795d06a100e4660ba57a500cbb206d9d849b
[root@server02 demo]# docker ps -a
CONTAINER ID   IMAGE             COMMAND                   CREATED             STATUS             PORTS                                                  NAMES
a8fd9609526f   docker-demo:1.0   "java -jar /app.jar"      54 seconds ago      Up 52 seconds      0.0.0.0:8080->8080/tcp, :::8080->8080/tcp              dd
dbf730d0ef60   mysql             "docker-entrypoint.s…"   About an hour ago   Up About an hour   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   mysql
c0f9d2c91c9d   nginx             "nginx -g 'daemon of…"   3 hours ago         Up 2 hours         0.0.0.0:90->80/tcp, :::90->80/tcp                      nginx
[root@server02 demo]#

网络


删除网络
[root@server02 demo]# docker network rm hmall
hmall
新增
[root@server02 demo]# docker network create wmmczk
462fcfdc6cb2467df985c1eee7c2ca355713321ca05646a4376ec73c8ed71c93

显示网络详情
[root@server02 demo]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
2479e9c603f8   bridge    bridge    local
18a3f1a81ca7   host      host      local
f3b8297a3f91   none      null      local
462fcfdc6cb2   wmmczk    bridge    local

将Mysql加入网络,并起别名db
[root@server02 demo]# docker network connect wmmczk mysql --alias db

将dd加入网络
[root@server02 demo]# docker network connect wmmczk dd
[root@server02 demo]# docker exec -it dd bash

从dd访问nysql 的别名db
root@a8fd9609526f:/# ping db
PING db (172.19.0.2) 56(84) bytes of data.
64 bytes from mysql.wmmczk (172.19.0.2): icmp_seq=1 ttl=64 time=0.152 ms
64 bytes from mysql.wmmczk (172.19.0.2): icmp_seq=2 ttl=64 time=0.151 ms
^C
--- db ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 3ms
rtt min/avg/max/mdev = 0.073/0.125/0.152/0.038 ms
root@a8fd9609526f:/# ping mysql
PING mysql (172.19.0.2) 56(84) bytes of data.
64 bytes from mysql.wmmczk (172.19.0.2): icmp_seq=1 ttl=64 time=0.258 ms
64 bytes from mysql.wmmczk (172.19.0.2): icmp_seq=2 ttl=64 time=0.098 ms
64 bytes from mysql.wmmczk (172.19.0.2): icmp_seq=3 ttl=64 time=0.072 ms
^C
--- mysql ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 4ms
rtt min/avg/max/mdev = 0.072/0.142/0.258/0.083 ms
root@a8fd9609526f:/#

创建容器时加入 --network 【容器名称】 就可直接加入网络,但是不加入默认网络。

项目部署

后端项目

[root@server02 demo]# cd /root
[root@server02 ~]# docker build -t hmall .
[+] Building 2.3s (8/8) FINISHED                                                                                                               docker:default
 => [internal] load build definition from Dockerfile                                                                                                     0.0s
 => => transferring dockerfile: 298B                                                                                                                     0.0s
 => [internal] load metadata for docker.io/library/openjdk:11.0-jre-buster                                                                               0.0s
 => [internal] load .dockerignore                                                                                                                        0.0s
 => => transferring context: 2B                                                                                                                          0.0s
 => [1/3] FROM docker.io/library/openjdk:11.0-jre-buster                                                                                                 0.0s
 => [internal] load build context                                                                                                                        0.7s
 => => transferring context: 68.24MB                                                                                                                     0.7s
 => CACHED [2/3] RUN ln -snf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo Asia/Shanghai > /etc/timezone                                      0.0s
 => [3/3] COPY hm-service.jar /app.jar                                                                                                                   1.2s
 => exporting to image                                                                                                                                   0.3s
 => => exporting layers                                                                                                                                  0.3s
 => => writing image sha256:97c798b4ad66621ffe0c767374828880c0a4b1fc060804c4b6bba53511f9bf24                                                             0.0s
 => => naming to docker.io/library/hmall                                                                                                                 0.0s
[root@server02 ~]# dis
REPOSITORY    TAG               IMAGE ID       CREATED          SIZE
hmall         latest            97c798b4ad66   5 seconds ago    370MB
docker-demo   1.0               9e95eddcf939   38 minutes ago   319MB
mysql         latest            be960704dfac   2 weeks ago      602MB
openjdk       11.0-jre-buster   57925f2e4cff   2 years ago      301MB
nginx         latest            3f8a4339aadd   6 years ago      108MB
[root@server02 ~]# docker rm -f dd
dd
[root@server02 ~]# docker run -d --name hm -p 8080:8080 --network wmmczk hmall
8de6cc8dcaf73d9452794482fb43327a617a7f7d1b4174baf03143bc1424f0f4
[root@server02 ~]# docker logs -f hm

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::               (v2.7.12)

23:13:45:771  INFO 1 --- [           main] com.hmall.HMallApplication               : Starting HMallApplication v1.0.0 using Java 11.0.13 on 8de6cc8dcaf7 with PID 1 (/app.jar started by root in /)
23:13:45:778 DEBUG 1 --- [           main] com.hmall.HMallApplication               : Running with Spring Boot v2.7.12, Spring v5.3.27
23:13:45:780  INFO 1 --- [           main] com.hmall.HMallApplication               : The following 1 profile is active: "dev"
23:13:48:750  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode
23:13:48:761  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode.
23:13:48:873  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 30 ms. Found 0 Redis repository interfaces.
23:13:51:096  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
23:13:51:130  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
23:13:51:131  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.75]
23:13:51:355  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
23:13:51:355  INFO 1 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 5400 ms
 _ _   |_  _ _|_. ___ _ |    _
| | |\/|_)(_| | |_\  |_)||_|_\
     /               |
                        3.4.3
23:13:57:392  INFO 1 --- [           main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [springfox.documentation.swagger2.web.Swagger2ControllerWebMvc#getDocumentation(String, HttpServletRequest)]
23:13:59:106  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
23:13:59:108  INFO 1 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Documentation plugins bootstrapped
23:13:59:116  INFO 1 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
23:13:59:356  INFO 1 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
23:14:00:473  INFO 1 --- [           main] com.hmall.HMallApplication               : Started HMallApplication in 16.316 seconds (JVM running for 17.706)

好了,我们已经熟悉了Docker的基本用法,接下来可以尝试部署项目了。

在课前资料中已经提供了一个黑马商城项目给大家,如图:

项目说明:

  • hmall:商城的后端代码

  • hmall-portal:商城用户端的前端代码

  • hmall-admin:商城管理端的前端代码

部署的容器及端口说明:

项目

容器名

端口

备注

hmall

hmall

8080

黑马商城后端API入口

hmall-portal

nginx

18080

黑马商城用户端入口

hmall-admin

18081

黑马商城管理端入口

mysql

mysql

3306

数据库

在正式部署前,我们先删除之前的nginx、dd两个容器:

 

docker rm -f nginx dd

mysql容器中已经准备好了商城的数据,所以就不再删除了。

3.1.部署Java项目

hmall项目是一个maven聚合项目,使用IDEA打开hmall项目,查看项目结构如图:

我们要部署的就是其中的hm-service,其中的配置文件采用了多环境的方式:

其中的application-dev.yaml是部署到开发环境的配置,application-local.yaml是本地运行时的配置。

查看application.yaml,你会发现其中的JDBC地址并未写死,而是读取变量:

这两个变量在application-dev.yamlapplication-local.yaml中并不相同:

在dev开发环境(也就是Docker部署时)采用了mysql作为地址,刚好是我们的mysql容器名,只要两者在一个网络,就一定能互相访问。

我们将项目打包:

结果:

hm-service目录下的Dockerfilehm-service/target目录下的hm-service.jar一起上传到虚拟机的root目录:

部署项目:

 

# 1.构建项目镜像,不指定tag,则默认为latest docker build -t hmall . # 2.查看镜像 docker images # 结果 REPOSITORY TAG IMAGE ID CREATED SIZE hmall latest 0bb07b2c34b9 43 seconds ago 362MB docker-demo 1.0 49743484da68 24 hours ago 327MB nginx latest 605c77e624dd 16 months ago 141MB mysql latest 3218b38490ce 17 months ago 516MB # 3.创建并运行容器,并通过--network将其加入hmall网络,这样才能通过容器名访问mysql docker run -d --name hmall --network hmall -p 8080:8080 hmall

测试,通过浏览器访问:http://你的虚拟机地址:8080/search/list

前端项目

删除原有的Nginx容器

[root@server02 ~]# docker rm -f nginx
nginx
[root@server02 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED        STATUS                      PORTS     NAMES
8de6cc8dcaf7   hmall     "java -jar /app.jar"      11 hours ago   Exited (143) 11 hours ago             hm
dbf730d0ef60   mysql     "docker-entrypoint.s…"   13 hours ago   Exited (0) 11 hours ago               mysql
[root@server02 ~]#

创建新Nginx容器并进行挂载和加入网络

修改配置文件(即后端容器的名字使前端可以访问后端):

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/json;

    sendfile        on;
    
    keepalive_timeout  65;

    server {
        listen       18080;
        # 指定前端项目所在的位置
        location / {
            root /usr/share/nginx/html/hmall-portal;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
        location /api {
            rewrite /api/(.*)  /$1 break;
            proxy_pass http://hm:8080;
        }
    }
    server {
        listen       18081;
        # 指定前端项目所在的位置
        location / {
            root /usr/share/nginx/html/hmall-admin;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
        location /api {
            rewrite /api/(.*)  /$1 break;
            proxy_pass http://hm:8080;
        }
    }
}

然后创建nginx容器并完成两个挂载:

  • /root/nginx/nginx.conf挂载到/etc/nginx/nginx.conf

  • /root/nginx/html挂载到/usr/share/nginx/html

由于需要让nginx同时代理hmall-portal和hmall-admin两套前端资源,因此我们需要暴露两个端口:

  • 18080:对应hmall-portal

  • 18081:对应hmall-admin

命令如下:

docker run -d \
  --name nginx \
  -p 18080:18080 \
  -p 18081:18081 \
  -v /root/nginx/html:/usr/share/nginx/html \
  -v /root/nginx/nginx.conf:/etc/nginx/nginx.conf \
  --network wmmczk\
  nginx

[root@server02 ~]# docker rm -f nginx
nginx
[root@server02 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED        STATUS                      PORTS     NAMES
8de6cc8dcaf7   hmall     "java -jar /app.jar"      11 hours ago   Exited (143) 11 hours ago             hm
dbf730d0ef60   mysql     "docker-entrypoint.s…"   13 hours ago   Exited (0) 11 hours ago               mysql
[root@server02 ~]# ^C
[root@server02 ~]# docker run -d \
>   --name nginx \
>   -p 18080:18080 \
>   -p 18081:18081 \
>   -v /root/nginx/html:/usr/share/nginx/html \
>   -v /root/nginx/nginx.conf:/etc/nginx/nginx.conf \
>   --network wmmczk\
>   nginx
c1330ae115775b962cf7582805e9feb010ea5b322fcfc3d9aea2a1fa7035eeaf
[root@server02 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED         STATUS                      PORTS     NAMES
c1330ae11577   nginx     "nginx -g 'daemon of…"   6 seconds ago   Exited (1) 4 seconds ago              nginx
8de6cc8dcaf7   hmall     "java -jar /app.jar"      11 hours ago    Exited (143) 11 hours ago             hm
dbf730d0ef60   mysql     "docker-entrypoint.s…"   13 hours ago    Exited (0) 11 hours ago               mysql
[root@server02 ~]# docker start nginx
nginx
[root@server02 ~]# docker start hm
hm
[root@server02 ~]# docker start mysql
mysql
[root@server02 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED              STATUS                      PORTS                                                  NAMES
c1330ae11577   nginx     "nginx -g 'daemon of…"   About a minute ago   Exited (1) 59 seconds ago                                                          nginx
8de6cc8dcaf7   hmall     "java -jar /app.jar"      11 hours ago         Up 46 seconds               0.0.0.0:8080->8080/tcp, :::8080->8080/tcp              hm
dbf730d0ef60   mysql     "docker-entrypoint.s…"   13 hours ago         Up 40 seconds               0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   mysql
[root@server02 ~]# docker start nginx
nginx
[root@server02 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED              STATUS              PORTS                                                                           NAMES
c1330ae11577   nginx     "nginx -g 'daemon of…"   About a minute ago   Up 5 seconds        80/tcp, 0.0.0.0:18080-18081->18080-18081/tcp, :::18080-18081->18080-18081/tcp   nginx
8de6cc8dcaf7   hmall     "java -jar /app.jar"      11 hours ago         Up About a minute   0.0.0.0:8080->8080/tcp, :::8080->8080/tcp                                       hm
dbf730d0ef60   mysql     "docker-entrypoint.s…"   13 hours ago         Up About a minute   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp                            mysql
[root@server02 ~]#

DockerCompose

docker run 参数

docker compose 指令

说明

--name

container_name

容器名称

-p

ports

端口映射

-e

environment

环境变量

-v

volumes

数据卷配置

--network

networks

网络

配置文件:

version: "3.8"

services:
  mysql:
    image: mysql
    container_name: mysql
    ports:
      - "3306:3306"
    environment:
      TZ: Asia/Shanghai
      MYSQL_ROOT_PASSWORD: 123
    volumes:
      - "./mysql/conf:/etc/mysql/conf.d"
      - "./mysql/data:/var/lib/mysql"
      - "./mysql/init:/docker-entrypoint-initdb.d"
    networks:
      - hm-net
  hmall:
    build: 
      context: .
      dockerfile: Dockerfile
    container_name: hmall
    ports:
      - "8080:8080"
    networks:
      - hm-net
    depends_on:
      - mysql
  nginx:
    image: nginx
    container_name: nginx
    ports:
      - "18080:18080"
      - "18081:18081"
    volumes:
      - "./nginx/nginx.conf:/etc/nginx/nginx.conf"
      - "./nginx/html:/usr/share/nginx/html"
    depends_on:
      - hmall
    networks:
      - hm-net
networks:
  hm-net:
    name: hmall

[root@server02 ~]# docker rm -f hm nginx mysql
hm
nginx
mysql
[root@server02 ~]# docker images
REPOSITORY    TAG               IMAGE ID       CREATED        SIZE
hmall         latest            97c798b4ad66   12 hours ago   370MB
docker-demo   1.0               9e95eddcf939   12 hours ago   319MB
mysql         latest            be960704dfac   2 weeks ago    602MB
openjdk       11.0-jre-buster   57925f2e4cff   2 years ago    301MB
nginx         latest            3f8a4339aadd   6 years ago    108MB
[root@server02 ~]# docker rmi hmall docker-demo
Untagged: hmall:latest
Deleted: sha256:97c798b4ad66621ffe0c767374828880c0a4b1fc060804c4b6bba53511f9bf24
Error response from daemon: No such image: docker-demo:latest
[root@server02 ~]# docker compose up -d
WARN[0000] /root/docker-compose.yml: `version` is obsolete
[+] Building 0.1s (8/8) FINISHED                                 docker:default
 => [hmall internal] load build definition from Dockerfile                 0.0s
 => => transferring dockerfile: 298B                                       0.0s
 => [hmall internal] load metadata for docker.io/library/openjdk:11.0-jre  0.0s
 => [hmall internal] load .dockerignore                                    0.0s
 => => transferring context: 2B                                            0.0s
 => [hmall internal] load build context                                    0.0s
 => => transferring context: 38B                                           0.0s
 => [hmall 1/3] FROM docker.io/library/openjdk:11.0-jre-buster             0.0s
 => CACHED [hmall 2/3] RUN ln -snf /usr/share/zoneinfo/Asia/Shanghai /etc  0.0s
 => CACHED [hmall 3/3] COPY hm-service.jar /app.jar                        0.0s
 => [hmall] exporting to image                                             0.0s
 => => exporting layers                                                    0.0s
 => => writing image sha256:3e78751a9f66a7824c8dd9a65bc7efa11c9e8def1e7be  0.0s
 => => naming to docker.io/library/root-hmall                              0.0s
[+] Running 4/4
 ✔ Network hmall    Created                                                0.1s
 ✔ Container mysql  Started                                                0.5s
 ✔ Container hmall  Started                                                0.9s
 ✔ Container nginx  Started                                                1.7s
[root@server02 ~]# docker compose images
WARN[0000] /root/docker-compose.yml: `version` is obsolete
CONTAINER           REPOSITORY          TAG                 IMAGE ID            SIZE
hmall               root-hmall          latest              3e78751a9f66        370MB
mysql               mysql               latest              be960704dfac        602MB
nginx               nginx               latest              3f8a4339aadd        108MB
[root@server02 ~]# docker compose ps
WARN[0000] /root/docker-compose.yml: `version` is obsolete
NAME      IMAGE        COMMAND                   SERVICE   CREATED         STATUS         PORTS
hmall     root-hmall   "java -jar /app.jar"      hmall     2 minutes ago   Up 2 minutes   0.0.0.0:8080->8080/tcp, :::8080->8080/tcp
mysql     mysql        "docker-entrypoint.s…"   mysql     2 minutes ago   Up 2 minutes   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp
nginx     nginx        "nginx -g 'daemon of…"   nginx     2 minutes ago   Up 2 minutes   80/tcp, 0.0.0.0:18080-18081->18080-18081/tcp, :::18080-18081->18080-18081/tcp
[root@server02 ~]#

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2231627.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

认证鉴权框架之—sa-token

一、概述 Satoken 是一个 Java 实现的权限认证框架&#xff0c;它主要用于 Web 应用程序的权限控制。Satoken 提供了丰富的功能来简化权限管理的过程&#xff0c;使得开发者可以更加专注于业务逻辑的开发。 二、逻辑流程 1、登录认证 &#xff08;1&#xff09;、创建token …

python爬虫实现自动获取论文GB 7714引用

在写中文论文、本硕博毕业设计的时候要求非常严格的引用格式——GB 7714引用。对于普通学生来说都是在google scholar上获取&#xff0c;一个一个输入点击很麻烦&#xff0c;就想使用python完成这个自动化流程&#xff0c;实现批量的倒入论文标题&#xff0c;导出引用。 正常引…

pycharm中python控制台出现CommandNotFoundError: No command ‘conda run‘.

1、错误现象 pycharm中打开python控制台出现CommandNotFoundError: No command conda run.的错误。 2、背景 conda是4.6版本&#xff0c;在Anaconda Prompt可以正常运行虚拟环境。 3、解决方法 更新conda版本&#xff0c;基本命令&#xff0c;会自动更新到最新版本。 con…

masm汇编字符输入小写转大写演示

从键盘读取一个字符变成大写换行并输出 assume cs:codecode segmentstart:mov ah,1int 21hmov bl,alsub bl,20hmov dl,10mov ah,2int 21hmov dl,blmov ah,2int 21hmov ah,4chint 21hcode ends end start 效果演示&#xff1a;

VisualStudio远程编译调试linux_c++程序(二)

前章讲述了gdb相关&#xff0c;这章主要讲述用VisualStudio调试编译linux_c程序 1&#xff1a;环境 win10 VisualStudio 2022 Community ubuntu22.04 2:安装 1>vs安装时&#xff0c;勾选 使用c进行linux 和嵌入式开发 (这里以vs2022为例) OR VS安装好了&#xff0c; 选择工…

【002】基于SpringBoot+thymeleaf实现的蓝天幼儿园管理系统

基于SpringBootthymeleaf实现的蓝天幼儿园管理系统 文章目录 系统说明技术选型成果展示账号地址及其他说明源码获取 系统说明 基于SpringBootthymeleaf实现的蓝天幼儿园管理系统是为幼儿园提供的一套管理平台&#xff0c;可以提高幼儿园信息管理的准确性&#xff0c;系统将信息…

【AIGC】从CoT到BoT:AGI推理能力提升24%的技术变革如何驱动ChatGPT未来发展

博客主页&#xff1a; [小ᶻZ࿆] 本文专栏: AIGC | ChatGPT 文章目录 &#x1f4af;前言&#x1f4af;迈向AGI的新跨越&#x1f4af;BoT与CoT的技术对比技术原理差异推理性能提升应用范围和通用性从错误中学习的能力总结 &#x1f4af;BoT的工作流程和机制初始化过程生成推…

无人机拦截捕获/直接摧毁算法详解!

一、无人机拦截捕获算法 网捕技术 原理&#xff1a;抛撒特殊设计的网具&#xff0c;捕获并固定无人机。 特点&#xff1a; 适用于小型无人机。 对无人机的损害较小&#xff0c;基本不影响其后续使用。 捕获成功率较高&#xff0c;且成本相对较低。 应用实例&#xff1a;…

解码层跑几次取决于输出词汇多少;10个单词,在解码层跑几次transformer

目录 解码层跑几次取决于输出词汇多少 10个单词,在解码层跑几次transformer 解码层跑几次取决于输出词汇多少 10个单词,在解码层跑几次transformer 取决于具体任务和输出要求 在自然语言处理任务中,Transformer 架构的解码器(Decoder)运行次数与你想要生成的输出长度有关…

算法【Java】—— 记忆化搜索

记忆化搜索 在前面我们已经学习了递归回溯等知识&#xff0c;什么是记忆化搜索&#xff0c;其实就是带着备忘录的递归&#xff0c;我们知道在递归过程中如果如果出现大量的重复的相同的子问题的时候&#xff0c;我们可能进行了多次递归&#xff0c;但是这些递归其实可以只用进…

优化EDM邮件营销,送达率与用户体验双赢

EDM邮件营销需选对平台&#xff0c;优化邮件列表&#xff0c;确保内容优质&#xff0c;进行邮件测试&#xff0c;关注用户反馈调整频率&#xff0c;以保高送达率&#xff0c;提升营销效果。 1. 了解电子邮件送达率的重要性 在开始优化邮件送达率之前&#xff0c;首先需要理解电…

Metasploit渗透测试之在云服务器中使用MSF

概述 随着云计算的发展&#xff0c;对基于云的应用程序、服务和基础设施的测试也在不断增加。在对云部署进行渗透测试时&#xff0c;最大的问题之一是共享所有权。过去&#xff0c;在进行渗透测试时&#xff0c;企业会拥有网络上的所有组件&#xff0c;我们可以对它们进行全部…

Qt桌面应用开发 第一天

目录 1.默认代码解析 1.1main.h解析 1.2myWidget.h解析 1.3FirstProject.pro解析&#xff08;FirstProject为创建的Qt项目名&#xff09; 2.命名规范与快捷键 3.按钮控件及窗口设置 3.1按钮控件QPushButton类 3.2窗口常用设计 4.Qt中的对象树 5.Qt中的坐标系 Qt是一个…

简记Vue3(三)—— ref、props、生命周期、hooks

个人简介 &#x1f440;个人主页&#xff1a; 前端杂货铺 &#x1f64b;‍♂️学习方向&#xff1a; 主攻前端方向&#xff0c;正逐渐往全干发展 &#x1f4c3;个人状态&#xff1a; 研发工程师&#xff0c;现效力于中国工业软件事业 &#x1f680;人生格言&#xff1a; 积跬步…

Mybatis查询数据库,返回List集合,集合元素也是List。

#有时间需求会要求&#xff1a;查询全校的学生数据&#xff0c;且学生数据按班级划分。那么就需要List<List<user>>类型的数据。 SQL语句 SELECT JSON_ARRAYAGG(JSON_OBJECT(name , name ,BJMC, BJMC ,BJBH,BJBH)) as dev_user FROM dev_user WHERE project_id …

Freertos学习日志(1)-基础知识

目录 1.什么是Freertos&#xff1f; 2.为什么要学习RTOS&#xff1f; 3.Freertos多任务处理的原理 1.什么是Freertos&#xff1f; RTOS&#xff0c;即&#xff08;Real Time Operating System 实时操作系统&#xff09;&#xff0c;是一种体积小巧、确定性强的计算机操作系统…

批量提取当前文件夹内的文件名

在需要提取的文件夹内新建一个txt文件&#xff0c;输入&#xff1a; dir ./b>name.txt 然后将该txt文件的扩展名改为.bat 如图 双击即可提取当前文件夹文件名&#xff0c;并保存到name.txt内

小林渗透入门:burpsuite+proxifier抓取小程序流量

目录 前提&#xff1a; 代理&#xff1a; proxifier&#xff1a; 步骤&#xff1a; bp证书安装 bp设置代理端口&#xff1a; proxifier设置规则&#xff1a; proxifier应用规则&#xff1a; 结果&#xff1a; 前提&#xff1a; 在介绍这两个工具具体实现方法之前&#xff0…

Node.js:session JWT

Node.js&#xff1a;session & JWT sessioncookiesessionexpress-session JWTexpress-jwt & jsonwebtoken session HTTP协议是无状态的&#xff0c;客户端的每次HTTP请求都是独立的&#xff0c;多个请求之间没有直接的关系&#xff0c;服务器不会保留每次HTTP请求的状…

后台管理系统的通用权限解决方案(七)SpringBoot整合SpringEvent实现操作日志记录(基于注解和切面实现)

1 Spring Event框架 除了记录程序运行日志&#xff0c;在实际项目中一般还会记录操作日志&#xff0c;包括操作类型、操作时间、操作员、管理员IP、操作原因等等&#xff08;一般叫审计&#xff09;。 操作日志一般保存在数据库&#xff0c;方便管理员查询。通常的做法在每个…