首页 > 其他分享 >docker

docker

时间:2023-01-31 23:22:06浏览次数:52  
标签:容器 tomcat -- docker root localhost

docker安装

参考阿里云工作台安装指导

image-20220121215128561

安装docker

linux安装docker

# step 1: 安装必要的一些系统工具
sudo yum install -y yum-utils device-mapper-persistent-data lvm2
# Step 2: 添加软件源信息
sudo yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
# Step 3: 更新并安装 Docker-CE
sudo yum makecache fast
sudo yum -y install docker-ce
# Step 4: 开启Docker服务
sudo service docker start

win10安装docker

1、安装 Hyper-V
右键开始菜单并以管理员身份运行 PowerShell,执行以下命令:
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All
2、下载安装docker,windows版本自带docker-compose
https://docs.docker.com/desktop/install/windows-install/

配置镜像加速器

sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://rcb2stnh.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

docker基本命令

帮助命令

docker COMMAND --help # docker帮助命令
Usage:  docker [OPTIONS] COMMAND

Options:
      --config string      Location of client config files (default "/root/.docker")
  -c, --context string     Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use")
  -D, --debug              Enable debug mode
  -H, --host list          Daemon socket(s) to connect to
  -l, --log-level string   Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
      --tls                Use TLS; implied by --tlsverify
      --tlscacert string   Trust certs signed only by this CA (default "/root/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/root/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/root/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

Management Commands:
  app*        Docker App (Docker Inc., v0.9.1-beta3)
  builder     Manage builds
  buildx*     Docker Buildx (Docker Inc., v0.7.1-docker)
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  image       Manage images
  manifest    Manage Docker image manifests and manifest lists
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  scan*       Docker Scan (Docker Inc., v0.12.0)
  secret      Manage Docker secrets
  service     Manage services
  stack       Manage Docker stacks
  swarm       Manage Swarm
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  build       Build an image from a Dockerfile
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container's filesystem
  events      Get real time events from the server
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a Docker registry
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  ps          List containers
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  search      Search the Docker Hub for images
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  version     Show the Docker version information
  wait        Block until one or more containers stop, then print their exit codes

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

镜像命令

搜索镜像

建议在DockerHub进行搜索

# docker search [OPTIONS] TERM
[root@localhost ~]# docker search tomcat
NAME                          DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
tomcat                        Apache Tomcat is an open source implementati…   3234      [OK]   
tomee                         Apache TomEE is an all-Apache Java EE certif…   94        [OK]   
dordoka/tomcat                Ubuntu 14.04, Oracle JDK 8 and Tomcat 8 base…   57                   [OK]
kubeguide/tomcat-app          Tomcat image for Chapter 1                      33             
consol/tomcat-7.0             Tomcat 7.0.57, 8080, "admin/admin"              18                   [OK]
cloudesire/tomcat             Tomcat server, 6/7/8                            15                   [OK]
aallam/tomcat-mysql           Debian, Oracle JDK, Tomcat & MySQL              12                   [OK]

查看本地镜像

[root@localhost ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
centos       latest    5d0da3dc9764   4 months ago   231MB

拉取镜像

#docker pull [OPTIONS] NAME[:TAG|@DIGEST]
[root@localhost ~]# docker pull tomcat 
Using default tag: latest
latest: Pulling from library/tomcat
0e29546d541c: Pull complete 
9b829c73b52b: Pull complete 
cb5b7ae36172: Pull complete 
6494e4811622: Pull complete 
668f6fcc5fa5: Pull complete 
dc120c3e0290: Pull complete 
8f7c0eebb7b1: Pull complete 
77b694f83996: Pull complete 
0f611256ec3a: Pull complete 
4f25def12f23: Pull complete 
Digest: sha256:9dee185c3b161cdfede1f5e35e8b56ebc9de88ed3a79526939701f3537a52324
Status: Downloaded newer image for tomcat:latest
docker.io/library/tomcat:latest

Docker镜像是分层构建的,拉取镜像也是分层拉取,拉取镜像是,不带标签默认拉取latest

删除镜像

# docker rmi [OPTIONS] IMAGE [IMAGE...]
[root@localhost cmatrix-2.0]# docker rmi centos:latest
Untagged: centos:latest
Untagged: centos@sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177
Deleted: sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6
Deleted: sha256:74ddd0ec08fa43d09f32636ba91a0a3053b02cb4627c35051aff89f853606b59

镜像分层

docker的镜像都是一层层的构建的,使用docker history可以看到镜像的构建过程

[root@localhost ~]# docker history centos
IMAGE          CREATED        CREATED BY                                      SIZE      COMMENT
5d0da3dc9764   4 months ago   /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B  
<missing>      4 months ago   /bin/sh -c #(nop)  LABEL org.label-schema.sc…   0B  
<missing>      4 months ago   /bin/sh -c #(nop) ADD file:805cb5e15fb6e0bb0…   231MB   

容器命令

运行容器

# docker run [OPTIONS] IMAGE [COMMAND] [ARG...]  在新容器中运行命令

docker run -d --name tomcat01 -p 8080:8080 -v /home/tomcat/webapps:/usr/local/tomcat/webapps tomcat
84caafb499657a3793e4d0fda7cd39f87c673c0b7e8b4003b99fc0c91fc6c20e

# -d         后台运行
# --name     容器名称
# -p         端口映射 宿主机端口:容器端口
# -v 		卷挂载   宿主机目录:容器目录
# -e         设置环境变量

docker容器开机自启动

使用--restart参数进行设置

容器退出时不重启容器
--restart=no
非0状态退出容器时,重启容器
--restart=on-failure
总是进行重启
--restart=always

如果再创建容器的时候没有指定--restart参数,可以使用docker update命令修改容器

进入容器

使用attach也可以进入容器,ctrl+c退出容器时容器会停止。

# docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
[root@localhost ~]# docker exec -it 84caafb49965 /bin/bash
root@84caafb49965:/usr/local/tomcat# 

停止容器

stop和kill命令均可停止容器,推荐使用stop,停止容器时,先发送SIGTERM信号,在一段时间之后(10s)再发送SIGKILL信号。而kill直接发送SIGKILL信号。

[root@localhost ~]# docker stop 84caafb49965
84caafb49965

查看容器

docker ps -a 查看所有容器
docker ps -f STATUS=exited # 查看状态为退出的容器

删除所有容器

[root@localhost ~]# docker ps -aq | xargs docker rm -f
84caafb49965
# 或者使用
[root@localhost ~]# docker rm -f $(docker ps -aq)

查看容器信息

[root@localhost ~]# docker inspect 84caafb49965
[
    {
        "Id": "84caafb499657a3793e4d0fda7cd39f87c673c0b7e8b4003b99fc0c91fc6c20e",
        "Created": "2022-01-22T13:09:44.171779819Z",
        "Path": "catalina.sh",
        "Args": [
            "run"

容器卷挂载信息

image-20220122211858493

容器端口映射信息

image-20220122211955252

查看容器端口映射

[root@localhost ~]# docker port 84caafb49965
8080/tcp -> 0.0.0.0:8080   #0.0.0.0表示本机的所有ipv4,一个主机可能存在多个网卡,多个ip地址
8080/tcp -> :::8080        #:: 表示本机的所有ipv6

复制文件

docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

将容器中的内容拷贝到宿主机

[root@localhost ~]# docker cp 7e9d7c0007b8:/home/testcp.txt ~/

将宿主机文件拷贝到容器

[root@localhost ~]# docker cp testtocontainer 7e9d7c0007b8:/home/

其他命令

查看Docker信息

[root@localhost ~]# docker info

image-20220122213614560

image-20220122213804602

容器数据卷

用于数据持久化,以及数据共享。

[root@localhost ~]# docker volume --help

Usage:  docker volume COMMAND

Manage volumes

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

创建容器卷

匿名卷,在创建时不指定卷的名称,具名卷,在创建时指定卷的名称。

docker run -v /宿主机路径:/容器路径 # 指定宿主机目录进行绑定,宿主机和容器都使用绝对路径
docker run -v 卷名:/容器路径 # 具名卷,卷名不使用/开头
docker run -v 容器路径 #匿名卷,容器会使用一段编码作为卷名

image-20220123152132959

查看卷信息

使用docker inspect命令分别查看3个容器

image-20220123152833833

查看卷挂载的宿主机路径

[root@localhost _data]# docker volume inspect testvolumes10
[
    {
        "CreatedAt": "2022-01-23T02:16:31-05:00",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/testvolumes10/_data", # 挂载在宿主机的位置
        "Name": "testvolumes10",
        "Options": null,
        "Scope": "local"
    }
]

容器数据卷共享

使用--volumes-from可以实现指定绑定路径具名卷匿名卷的数据共享。

# 1 创建一个具名卷容器
[root@localhost ~]# docker run -itd -v share:/home/share --name centos01 centos
bdb92adf64cd25ee3f1ad53efa2492e90ca736be25a44d93019dbaa305cdab47
# 2 创建另一个容器,共享第一个容器的数据卷
[root@localhost ~]# docker run -itd --volumes-from centos01 --name centos02 centos
b2d779aa9e249f24172f8bc7e85a3ea050dd6d6a94446500d73624aaab9d7470
# 3 测试,给第一个容器共享路径下创建一个文件,查看第二容器中是否存在
[root@localhost ~]# docker exec centos01 touch /home/share/test1
[root@localhost ~]# docker exec centos02 ls /home/share/
test1
# 4 测试,修改宿主机文件,并查看两个容器是否修改
[root@localhost ~]# docker volume inspect share
[
    {
        "CreatedAt": "2022-01-27T20:30:47-05:00",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/share/_data",
        "Name": "share",
        "Options": null,
        "Scope": "local"
    }
]
[root@localhost ~]# cd /var/lib/docker/volumes/share/_data
[root@localhost _data]# ls
test1
[root@localhost _data]# echo "hello" >> test1
[root@localhost _data]# more test1 
hello
[root@localhost _data]# docker exec centos01 cat /home/share/test1
hello
[root@localhost _data]# docker exec centos02 cat /home/share/test1
hello

DockerFile

使用DockerFile可以构建自己的镜像

使用commit构建镜像(不推荐)

Docker是分层的,当我们运行一个容器的时候,我们在容器里边的每一个操作,都相当于是给镜像添加新的层,使用commit便可以保存我们在容器中的操作,形成新的镜像。

[root@localhost ~]# docker commit --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 <[email protected]>")
  -c, --change list      Apply Dockerfile instruction to the created image
  -m, --message string   Commit message
  -p, --pause            Pause container during commit (default true)
[root@localhost ~]# docker commit -a "zsummer <[email protected]>" -m "cp webapps.dist to webapps" 358b2385097e mytomcat:1.0
sha256:7115ea997dd3bf3df3f7f2ef7389ce83bb9a559e9357067018cf0d47eab9a2bc

DockFile命令

image-20220130144836930\

补充 :

ENV: 指定运行环境变量。

CMD和RUN的区别:CMD指定容器启动后要执行的命令,RUN是构建镜像build时需要用到的命令。

CMD和ENTRYPOINT的区别:CMD为容器启动后默认要干的事,一个Dockerfile只有1个CMD生效,如果有多个只有最后一个生效。ENTRYPOINT容器启动后需要干的事,不会被覆盖。

官方指导文档地址

https://docs.docker.com/engine/reference/builder/

查看dockerhub镜像仓库中的dockerfile

image-20220128102123577

image-20220128102240323

tomcat最新镜像的Dockerfile文件

#
# NOTE: THIS DOCKERFILE IS GENERATED VIA "apply-templates.sh"
#
# PLEASE DO NOT EDIT IT DIRECTLY.
#

# 设置基础镜像
FROM openjdk:17-jdk-bullseye

# 设置环境变量
ENV CATALINA_HOME /usr/local/tomcat
ENV PATH $CATALINA_HOME/bin:$PATH
# 构建时运行的命令
RUN mkdir -p "$CATALINA_HOME"
# 设置工作目录,我们进入容器后的目录
WORKDIR $CATALINA_HOME

# let "Tomcat Native" live somewhere isolated
ENV TOMCAT_NATIVE_LIBDIR $CATALINA_HOME/native-jni-lib
ENV LD_LIBRARY_PATH ${LD_LIBRARY_PATH:+$LD_LIBRARY_PATH:}$TOMCAT_NATIVE_LIBDIR

# see https://www.apache.org/dist/tomcat/tomcat-10/KEYS
# see also "versions.sh" (https://github.com/docker-library/tomcat/blob/master/versions.sh)
ENV GPG_KEYS A9C5DF4D22E99998D9875A5110C01C5A2F6059E7

ENV TOMCAT_MAJOR 10
ENV TOMCAT_VERSION 10.1.0-M10
ENV TOMCAT_SHA512 ec744e2151a4c9d50728efc0f97a4132e9cbcbf0a643621d7676115d4d59d174bde313512346d52cd53ac1f96ed31e0503e7c430dd61ada35a4c2e70d26e0532

RUN set -eux; \
	\
	savedAptMark="$(apt-mark showmanual)"; \
	apt-get update; \
	apt-get install -y --no-install-recommends \
		ca-certificates \
		curl \
		dirmngr \
		gnupg \
	; \
	\
	ddist() { \
		local f="$1"; shift; \
		local distFile="$1"; shift; \
		local mvnFile="${1:-}"; \
		local success=; \
		local distUrl=; \
		for distUrl in \
# https://issues.apache.org/jira/browse/INFRA-8753?focusedCommentId=14735394#comment-14735394
			"https://www.apache.org/dyn/closer.cgi?action=download&filename=$distFile" \
# if the version is outdated (or we're grabbing the .asc file), we might have to pull from the dist/archive :/
			"https://downloads.apache.org/$distFile" \
			"https://www-us.apache.org/dist/$distFile" \
			"https://www.apache.org/dist/$distFile" \
			"https://archive.apache.org/dist/$distFile" \
# if all else fails, let's try Maven (https://www.mail-archive.com/[email protected]/msg134940.html; https://mvnrepository.com/artifact/org.apache.tomcat/tomcat; https://repo1.maven.org/maven2/org/apache/tomcat/tomcat/)
			${mvnFile:+"https://repo1.maven.org/maven2/org/apache/tomcat/tomcat/$mvnFile"} \
		; do \
			if curl -fL -o "$f" "$distUrl" && [ -s "$f" ]; then \
				success=1; \
				break; \
			fi; \
		done; \
		[ -n "$success" ]; \
	}; \
	\
	ddist 'tomcat.tar.gz' "tomcat/tomcat-$TOMCAT_MAJOR/v$TOMCAT_VERSION/bin/apache-tomcat-$TOMCAT_VERSION.tar.gz" "$TOMCAT_VERSION/tomcat-$TOMCAT_VERSION.tar.gz"; \
	echo "$TOMCAT_SHA512 *tomcat.tar.gz" | sha512sum --strict --check -; \
	ddist 'tomcat.tar.gz.asc' "tomcat/tomcat-$TOMCAT_MAJOR/v$TOMCAT_VERSION/bin/apache-tomcat-$TOMCAT_VERSION.tar.gz.asc" "$TOMCAT_VERSION/tomcat-$TOMCAT_VERSION.tar.gz.asc"; \
	export GNUPGHOME="$(mktemp -d)"; \
	for key in $GPG_KEYS; do \
		gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key"; \
	done; \
	gpg --batch --verify tomcat.tar.gz.asc tomcat.tar.gz; \
	tar -xf tomcat.tar.gz --strip-components=1; \
	rm bin/*.bat; \
	rm tomcat.tar.gz*; \
	command -v gpgconf && gpgconf --kill all || :; \
	rm -rf "$GNUPGHOME"; \
	\
# https://tomcat.apache.org/tomcat-9.0-doc/security-howto.html#Default_web_applications
	mv webapps webapps.dist; \
	mkdir webapps; \
# we don't delete them completely because they're frankly a pain to get back for users who do want them, and they're generally tiny (~7MB)
	\
	nativeBuildDir="$(mktemp -d)"; \
	tar -xf bin/tomcat-native.tar.gz -C "$nativeBuildDir" --strip-components=1; \
	apt-get install -y --no-install-recommends \
		dpkg-dev \
		gcc \
		libapr1-dev \
		libssl-dev \
		make \
	; \
	( \
		export CATALINA_HOME="$PWD"; \
		cd "$nativeBuildDir/native"; \
		gnuArch="$(dpkg-architecture --query DEB_BUILD_GNU_TYPE)"; \
		aprConfig="$(command -v apr-1-config)"; \
		./configure \
			--build="$gnuArch" \
			--libdir="$TOMCAT_NATIVE_LIBDIR" \
			--prefix="$CATALINA_HOME" \
			--with-apr="$aprConfig" \
			--with-java-home="$JAVA_HOME" \
			--with-ssl=yes \
		; \
		nproc="$(nproc)"; \
		make -j "$nproc"; \
		make install; \
	); \
	rm -rf "$nativeBuildDir"; \
	rm bin/tomcat-native.tar.gz; \
	\
# reset apt-mark's "manual" list so that "purge --auto-remove" will remove all build dependencies
	apt-mark auto '.*' > /dev/null; \
	[ -z "$savedAptMark" ] || apt-mark manual $savedAptMark > /dev/null; \
	find "$TOMCAT_NATIVE_LIBDIR" -type f -executable -exec ldd '{}' ';' \
		| awk '/=>/ { print $(NF-1) }' \
		| xargs -rt readlink -e \
		| sort -u \
		| xargs -rt dpkg-query --search \
		| cut -d: -f1 \
		| sort -u \
		| tee "$TOMCAT_NATIVE_LIBDIR/.dependencies.txt" \
		| xargs -r apt-mark manual \
	; \
	\
	apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \
	rm -rf /var/lib/apt/lists/*; \
	\
# sh removes env vars it doesn't support (ones with periods)
# https://github.com/docker-library/tomcat/issues/77
	find ./bin/ -name '*.sh' -exec sed -ri 's|^#!/bin/sh$|#!/usr/bin/env bash|' '{}' +; \
	\
# fix permissions (especially for running as non-root)
# https://github.com/docker-library/tomcat/issues/35
	chmod -R +rX .; \
	chmod 777 logs temp work; \
	\
# smoke test
	catalina.sh version

# verify Tomcat Native is working properly
RUN set -eux; \
	nativeLines="$(catalina.sh configtest 2>&1)"; \
	nativeLines="$(echo "$nativeLines" | grep 'Apache Tomcat Native')"; \
	nativeLines="$(echo "$nativeLines" | sort -u)"; \
	if ! echo "$nativeLines" | grep -E 'INFO: Loaded( APR based)? Apache Tomcat Native library' >&2; then \
		echo >&2 "$nativeLines"; \
		exit 1; \
	fi
# 暴露端口
EXPOSE 8080
# 默认启动容器后执行的命令
CMD ["catalina.sh", "run"]

使用build命令构建镜像

[root@localhost myDockerfile]# docker build --help

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

Build an image from a Dockerfile

命令中的PATH指需要发送到docker引擎的文件路径。因为客户端需要将文件发送给docker引擎,然后由docker引擎进行构建,并非指Dockerfile的位置。Dockerfile的位置由-f参数进行指定。通常PATH我们写. 意思是将当前目录下的所有文件发送给docker引擎。不需要发送给docker引擎的文件定义在.dockerignore文件中

自己写一个Dockerfile

1、创建Dockerfile文件,文件命名为Dockerfile,可以不用使用-f参数指定文件位置,默认使用当前文件下的Dockerfile文件构建

image-20220129123233251

FROM centos
MAINTAINER zsummer<[email protected]>
RUN mkdir -p /home/zhouyujiang
RUN mkdir -p /home/zsummer
RUN touch /home/zsummer/aa; \
chmod 777 /home/zsummer/aa
ADD ./cpTxt /home/zsummer
WORKDIR /home/zsummer
VOLUME ["v1:/home/zsummer", "v2:/home/zhouyujiang"]
EXPOSE 8888
CMD ["echo", "1000"]

2、构建镜像

执行构建命令的返回信息Sending build context to Docker daemon 3.072kB可以看出,使用“.”Dockerfile将本地目录下的文件发送到Docker引擎进行构建,并非在客户端进行构建。每一句命令都会生成一个镜像层。

[root@localhost myDockerfile]# docker build -t zsummer/mycentos:1.0 .
Sending build context to Docker daemon  3.072kB
Step 1/10 : FROM centos
 ---> 5d0da3dc9764
Step 2/10 : MAINTAINER zsummer<[email protected]>
 ---> Running in 853e4e4c643f
Removing intermediate container 853e4e4c643f
 ---> d592e1cb0bc2
Step 3/10 : RUN mkdir -p /home/zhouyujiang
 ---> Running in 38531136a3d5
Removing intermediate container 38531136a3d5
 ---> 1be3ecaf79f8
Step 4/10 : RUN mkdir -p /home/zsummer
 ---> Running in 4ae890c71bbc
Removing intermediate container 4ae890c71bbc
 ---> 2ac88f4dfe59
Step 5/10 : RUN touch /home/zsummer/aa; chmod 777 /home/zsummer/aa
 ---> Running in c2043c571055
Removing intermediate container c2043c571055
 ---> 7fd4be15c9f2
Step 6/10 : ADD ./cpTxt /home/zsummer
 ---> e4b89c91386c
Step 7/10 : WORKDIR /home/zsummer
 ---> Running in c03cc337d677
Removing intermediate container c03cc337d677
 ---> e2929c6649b7
Step 8/10 : VOLUME ["v1:/home/zsummer", "v2:/home/zhouyujiang"]
 ---> Running in f5b78253ea47
Removing intermediate container f5b78253ea47
 ---> a9380123744e
Step 9/10 : EXPOSE 8888
 ---> Running in c2a828b55fc8
Removing intermediate container c2a828b55fc8
 ---> eec4236e55c7
Step 10/10 : CMD ["echo", "1000"]
 ---> Running in 7cab7e334eaf
Removing intermediate container 7cab7e334eaf
 ---> f8816ae66e0e
Successfully built f8816ae66e0e
Successfully tagged zsummer/mycentos:1.0

自己构建一个Springboot的镜像

1、写一个springboot的项目、打包后发送到服务器

image-20220130123348861

FROM java:8
MAINTAINER zsummer<[email protected]>
ENV app_home=/home/app/hello
ENV jar_name=hello-world-0.0.1-SNAPSHOT.jar
RUN mkdir -p ${app_home}
ADD /target/${jar_name} ${app_home}
EXPOSE 8080
CMD java -jar ${app_home}/${jar_name}

2、使用Docker客户端构建镜像

[root@localhost hello]# docker run -it --name myhello -p 8080:8080 hello:2.0
Unable to find image 'hello:2.0' locally
^C
[root@localhost hello]# docker build -t hello:2.0 .
Sending build context to Docker daemon  17.56MB
Step 1/8 : FROM java:8
 ---> d23bdf5b1b1b
Step 2/8 : MAINTAINER zsummer<[email protected]>
 ---> Using cache
 ---> b94348f7da4d
Step 3/8 : ENV app_home=/home/app/hello
 ---> Using cache
 ---> a901b19ad73c
Step 4/8 : ENV jar_name=hello-world-0.0.1-SNAPSHOT.jar
 ---> Using cache
 ---> 40701353c7ad
Step 5/8 : RUN mkdir -p ${app_home}
 ---> Using cache
 ---> 33fe8968f81c
Step 6/8 : ADD /target/${jar_name} ${app_home}
 ---> Using cache
 ---> 5023ec70e99a
Step 7/8 : EXPOSE 8080
 ---> Using cache
 ---> 97cd475b0fbb
Step 8/8 : CMD java -jar ${app_home}/${jar_name}
 ---> Running in 53d4268b668e
Removing intermediate container 53d4268b668e
 ---> 3acee2b22cd4
Successfully built 3acee2b22cd4
Successfully tagged hello:2.0

3、运行镜像

[root@localhost hello]# docker run -it --name myhello3 -p 8080:8080 -d  hello:2.0
0e2d5a7844ea25f0c20defcd9f6c7ec97fd43d4cfdb46640fe7f0cee3ac9af5

4、访问测试

[root@localhost hello]# curl localhost:8080/hello
hello world

Docker网络

docker0

docker0是docker自己创建的默认的网络。运行容器不指定网络的情况下,默认使用docker0.在实际应用中推荐自己创建网络,一方面可以进行网络隔离,其次自己创建的网络,默认可以使用容器名,容器id进行访问。

image-20220130123736779

docker0探究

只启动两个容器,查看宿主机网络信息

image-20220130124949192

分别查看两个容器网络信息, docker0的ip地址为172.17.0.1/16 两个容器的ip分别是172.17.0.1/16,172.17.0.2/16。使用的技术是veth,他们是成对出现的。如宿主机的49: veth48fa79d@if48和容器的48: eth0@if49

image-20220130125127361

image-20220130125143513

image-20220130132429954

容器间使用主机名访问

docker创建容器默认使用docker0.容器间可以使用ip地址进行访问。

使用--link可以实现主机名访问的需求,该命令本质上是修改容器的hosts文件, 不推荐这种方式,比较推荐自建网络的方式。

[root@localhost hello]# docker run -it --name centos03 --link centos02 --link centos01 -d centos
bae9067a7be59b0baec441a4e615ca8bd78bdba7138717a891b461c25d394502

image-20220130135744799

创建网络

查看网络

docker0就是下面的f7f941a1a34a bridge bridge local。使用的是桥接模式的网络,docker默认创建的还有host null两种模式。

[root@localhost hello]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
f7f941a1a34a   bridge    bridge    local
39a76d3dcf15   host      host      local
443ade7cae91   none      null      local
[root@localhost hello]# docker network inspect f7f941a1a34a
[
    {
        "Name": "bridge",
        "Id": "f7f941a1a34a347e9eb3d471b8bc27d4de679fdb9a2c67809055ec5f7009ca6f",
        "Created": "2022-01-27T19:49:03.760751502-05:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "76ed606d8d7c21e2782eb5aa14b8061d0e51b669acbc2d1e02ef9745ed1dad26": {
                "Name": "centos02",
                "EndpointID": "ba7de22e9fe475a457520dbc75d9b6554a2d6d209fbd417814aa10e28b521e97",
                "MacAddress": "02:42:ac:11:00:03",
                "IPv4Address": "172.17.0.3/16",
                "IPv6Address": ""
            },
            "7b91b399105cd21ae4bebc8856974f3c3e145011188ed1f8e241319f6ff6390b": {
                "Name": "centos01",
                "EndpointID": "d5230214876bf90d223396473550a0862b2fef6d9be2a92a8ba48929613e5e82",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            },
            "bae9067a7be59b0baec441a4e615ca8bd78bdba7138717a891b461c25d394502": {
                "Name": "centos03",
                "EndpointID": "110134b3283ac3dbb723712f2b9d62a5457efc157d9670155d4ee0f474f2ad2b",
                "MacAddress": "02:42:ac:11:00:04",
                "IPv4Address": "172.17.0.4/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]

创建网络

[root@localhost hello]#  docker network create \
>   --driver=bridge \
>   --subnet=172.28.0.0/16 \
>   --gateway=172.28.0.1 \
>   my-net
1fcb2053949902e98ec2196a663deccf4daff07c2044af356d1e3f9d8a123277

--driver配置网络模式,默认bridge

--subnet配置子网

--gateway配置网络,不写的话默认使用子网的.1地址作为网关

image-20220130142645836

image-20220130142848700

运行容器并指定网络

[root@localhost hello]# docker run -it --name centos01 --network my-net -d centos
935ad34ab8273a0aad79fdaa791e610faa43a35b9267c1e67dbcc6026ad62a22
[root@localhost hello]# docker run -it --name centos02 --network my-net -d centos
26126fac5645f1816a4c8920def269e3d022cf20af0f5df157c280a3c155f069

使用自定义的网络,可以直接通过主机名或者容器ID进行访问

image-20220130143242487

image-20220130143934331

总结

Docker常用指令

image-20220123114305469

Docker集群

DockerCompose

K8s

架构

集群搭建

Pod

控制器类型

网络通讯模式

资源清单

Pod控制器

服务发现

存储

调度器

集群安全机制

HELM

标签:容器,tomcat,--,docker,root,localhost
From: https://www.cnblogs.com/zhouyujiang/p/17081159.html

相关文章

  • Docker部署Nacos自动停止运行
    1、现象使用docker部署的Nacos在运行一段时间后,就自动停止运行了。查看docker运行容器,nacos停止了2、解决因为是学生购买的轻量级服务器,所以配置很低,出现这种问题我默......
  • [Docker] Create a Docker image with Dockerfile
    ###Createadockerfile1.Cdtotheproject:`cdwidget-factory-inc/`2.createadockerfile:`vimdockerfile````bashFROMhttpd:2.4RUNaptupdate-y&&......
  • docker仓库登录出错
    Errorsavingcredentials:errorstoringcredentials-err:exitstatus1,CannotautolaunchD-BuswithoutX11$DISPLAY`出错提示:errorstoringcredentials-er......
  • Docker-consul的容器服务更新与发现
    一、Consul概述1.1什么是服务注册与发现服务注册与发现是微服务架构中不可或缺的重要组件。起初服务都是单节点的,不保障高可用性,也不考虑服务的压力承载,服务之间调用单纯......
  • Docker的基本概念
    Docker的基本概念......
  • Docker 安装 MySQL5.7
    1.拉取数据库镜像dockerpullmysql:5.7 dockerimages命令查看镜像是否下载成功dockerimages2.配置mysql创建mysql目录,用于存放mysql相关配置及数据mkdir-p......
  • 关于Docker-Docker引擎
    详解:http://c.biancheng.net/view/3137.html下载与使用:https://blog.csdn.net/qq_44074697/article/details/118569644?ops_request_misc=%257B%2522request%255Fid%2522%......
  • Jenkins pipeline 使用agent docker编译构建
    Jenkins使用agentdocker构建pipeline此处用于记录,使用jenkinspipeline构建时,使用docker启动一个agent来构建编译环境。//需要在jenkins的Credentials设置中配置......
  • ubuntu 非root用户启动docker
    启动运行minikubeminikubestart--image-mirror-country='cn'......
  • docker-mysql cmd
    version:'3'services:db:#构建mysql镜像image:mysqlnetworks:network1:ipv4_address:172.16.238.10ip......