Docker入门
-
Docker概述
Docker为什么会出现?
考虑一种情况,有一种产品,有开发和上线两种环境!应用环境,应用配置!
开发-----运维。问题:我在我的电脑上可以运行!版本更新,导致服务不可用!对于运维来说,考验就十分大?
环境配置是十分麻烦的,每一台机器都需要部署环境(集群Redis,ES,Hadoop....)费时费力。
发布一个项目 (jar+(Redis MySQL jdk ES)),项目能不能带上环境安装打包!
例如:
之前在一个服务器配置一个应用的环境 Redis MySQL jdk Hadoop.配置起来超麻烦,不能够跨平台。
Windows开发,最后发布在Linux!
传统:开发jar,环境由运维来做!
现在:开发打包部署上线,一套流程做完!
Docker给以上问题提供了解决方案
举个例子:
手机软件开发流程:
java ---> apk --->发布(应用商店) ---> 第三方使用apk --->安装即可用
相对应的,Docker优化jar包开发部署流程:
java ---> jar(环境) ---> 打包带上环境(镜像)--->(Docker仓库:对应应用商店)---> 下载我们发布的镜像 ---> 直接运行即可!

Docker的思想来自于集装箱!
原本 JRE---多个应用(端口冲突)----原来都是交叉的!
隔离:Docker核心思想!打包装箱!每个箱子都是互相隔离的。
Docker 通过隔离机制,可以将服务器压榨到机制
Docker历史
2010年,几个搞IT的年轻人,就在美国成立了一家公司dotCloud
做一些pass的云计算服务!LXC有关的容器技术!
他们将自己的技术(容器化技术)命名为Docker!
Docker刚刚诞生的时候,没有引起行业的注意!dotCloud,就活不下去了!
开源
开放源代码!
2013年,Docker开源!
Docker越来越多的人发现了docker的优点!火了,Docker每个月都会更新一个版本!
2014年4月9日,Docker1.0发布!
Dcoker为什么这么火?十分的轻巧!
在容器技术出现之前我们使用的都是虚拟机技术!
虚拟机:在window中安装一个Vmware,通过这个软件我们可以虚拟出来一台或者多台电脑!缺点:笨重!
虚拟机也是虚拟化技术,Docker容器技术,也是一种虚拟化技术!
vm:linux centos原生镜像(一个电脑!) 隔离:需要开启多台虚拟机! 几个G
docker:隔离,镜像(最核心的环境:4m+jdk+mysql) 十分的小巧,运行镜像就可以了!小巧!几个M
到现在,所有的开发/运维人员都必须掌握Docker!
聊聊Docker
Docker是基于Go语言开发的!开源项目!
Docker可以干什么?
之前的虚拟机技术
- 资源占用十分多
- 冗余步骤多
- 启动十分满

容器技术不是模拟一个完整的操作系统

比较Docker和虚拟机技术的不同:
传统虚拟机,虚拟出一个硬件,运行一个完整的操作系统,然后再这个系统上安装和运行软件
容器内的应用直接运行在宿主机的内容,容器是没有内核的,也没有虚拟我们的硬件,也没有虚拟我们的硬件,所以就轻便了
每个容器之间是互相隔离,每个容器都有一个属于自己的文件系统,互不影响。
DevOps(开发,运维)
更快速的交付和部署
传统:一堆帮助文档,安装成簇
Docker:一键运行打包发布测试,一键运行
更便捷的升级和扩缩容
使用了Docker之后,我们部署应用就和搭积木一样!
项目打包成一个镜像,扩展 服务器B,服务器B一键运行
更简单的系统运维
在容器化之后,我们的开发,测试环境都是高度的一致。
更高效的计算资源利用
Docker是内核级别的虚拟化,可以在一个物理机上运行很多的容器实例!
-
Docker安装
Docker架构图


镜像(iamge):
docker镜像就好比一个模板,可以通过这个模板来创建容器服务,tomcat镜像===》run===>tomcat01容器(提供服务器)
通过这个容器可以创建多个容器(最终服务运行或者项目运行就是在容器中的)。
容器(container):
Docker利用容器技术,独立运行一个或者一组应用,通过镜像来创建的。
启动,停止,删除,基本命令!
目前就可以把这个容器理解为一个简单的linux系统
仓库(repository):
仓库就是存放镜像的地方!
仓库可以分为共有仓库和私有仓库!
Docker Hub
阿里云...都有容器服务器(配置镜像加速!)
Docker安装步骤
环境准备
#系统内核是3.10以上的
[root@iZ2zec2gz7h1jgw8klihsnZ /]# uname -r 3.10.0-1062.18.1.el7.x86_64
#系统版本 [root@iZ2zec2gz7h1jgw8klihsnZ /]# cat /etc/os-release NAME="CentOS Linux" VERSION="7 (Core)" ID="centos" ID_LIKE="rhel fedora" VERSION_ID="7" PRETTY_NAME="CentOS Linux 7 (Core)" ANSI_COLOR="0;31" CPE_NAME="cpe:/o:centos:centos:7" HOME_URL="https://www.centos.org/" BUG_REPORT_URL="https://bugs.centos.org/" CENTOS_MANTISBT_PROJECT="CentOS-7" CENTOS_MANTISBT_PROJECT_VERSION="7" REDHAT_SUPPORT_PRODUCT="centos" REDHAT_SUPPORT_PRODUCT_VERSION="7"
Centos7安装
#1.卸载旧的版本 [root@iZ2zec2gz7h1jgw8klihsnZ /]# yum remove docker \ > docker-client \ > docker-client-latest \ > docker-common \ > docker-latest \ > docker-latest-logrotate \ > docker-logrotate \ > docker-engine Loaded plugins: fastestmirror No Match for argument: docker No Match for argument: docker-client No Match for argument: docker-client-latest No Match for argument: docker-common No Match for argument: docker-latest No Match for argument: docker-latest-logrotate No Match for argument: docker-logrotate No Match for argument: docker-engine No Packages marked for removal
#2。安装安装包 [root@iZ2zec2gz7h1jgw8klihsnZ /]# yum install -y yum-utils Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile base | 3.6 kB 00:00:00 epel | 4.7 kB 00:00:00 extras | 2.9 kB 00:00:00 updates | 2.9 kB 00:00:00 Resolving Dependencies --> Running transaction check ---> Package yum-utils.noarch 0:1.1.31-54.el7_8 will be installed --> Processing Dependency: python-kitchen for package: yum-utils-1.1.31-54.el7_8.noarch --> Processing Dependency: libxml2-python for package: yum-utils-1.1.31-54.el7_8.noarch --> Running transaction check ---> Package libxml2-python.x86_64 0:2.9.1-6.el7_9.6 will be installed --> Processing Dependency: libxml2 = 2.9.1-6.el7_9.6 for package: libxml2-python-2.9.1-6.el7_9.6.x86_64 ---> Package python-kitchen.noarch 0:1.1.1-5.el7 will be installed --> Processing Dependency: python-chardet for package: python-kitchen-1.1.1-5.el7.noarch --> Running transaction check ---> Package libxml2.x86_64 0:2.9.1-6.el7_2.3 will be updated ---> Package libxml2.x86_64 0:2.9.1-6.el7_9.6 will be an update ---> Package python-chardet.noarch 0:2.2.1-3.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved ======================================================================================================================================= Package Arch Version Repository Size ======================================================================================================================================= Installing: yum-utils noarch 1.1.31-54.el7_8 base 122 k Installing for dependencies: libxml2-python x86_64 2.9.1-6.el7_9.6 updates 247 k python-chardet noarch 2.2.1-3.el7 base 227 k python-kitchen noarch 1.1.1-5.el7 base 267 k Updating for dependencies: libxml2 x86_64 2.9.1-6.el7_9.6 updates 668 k Transaction Summary ======================================================================================================================================= Install 1 Package (+3 Dependent packages) Upgrade ( 1 Dependent package) Total download size: 1.5 M Downloading packages: Delta RPMs disabled because /usr/bin/applydeltarpm not installed. (1/5): python-kitchen-1.1.1-5.el7.noarch.rpm | 267 kB 00:00:00 (2/5): libxml2-2.9.1-6.el7_9.6.x86_64.rpm | 668 kB 00:00:00 (3/5): yum-utils-1.1.31-54.el7_8.noarch.rpm | 122 kB 00:00:00 (4/5): python-chardet-2.2.1-3.el7.noarch.rpm | 227 kB 00:00:00 (5/5): libxml2-python-2.9.1-6.el7_9.6.x86_64.rpm | 247 kB 00:00:00 --------------------------------------------------------------------------------------------------------------------------------------- Total 4.9 MB/s | 1.5 MB 00:00:00 Running transaction check Running transaction test Transaction test succeeded Running transaction Updating : libxml2-2.9.1-6.el7_9.6.x86_64 1/6 Installing : libxml2-python-2.9.1-6.el7_9.6.x86_64 2/6 Installing : python-chardet-2.2.1-3.el7.noarch 3/6 Installing : python-kitchen-1.1.1-5.el7.noarch 4/6 Installing : yum-utils-1.1.31-54.el7_8.noarch 5/6 Cleanup : libxml2-2.9.1-6.el7_2.3.x86_64 6/6 Verifying : python-chardet-2.2.1-3.el7.noarch 1/6 Verifying : libxml2-2.9.1-6.el7_9.6.x86_64 2/6 Verifying : libxml2-python-2.9.1-6.el7_9.6.x86_64 3/6 Verifying : python-kitchen-1.1.1-5.el7.noarch 4/6 Verifying : yum-utils-1.1.31-54.el7_8.noarch 5/6 Verifying : libxml2-2.9.1-6.el7_2.3.x86_64 6/6 Installed: yum-utils.noarch 0:1.1.31-54.el7_8 Dependency Installed: libxml2-python.x86_64 0:2.9.1-6.el7_9.6 python-chardet.noarch 0:2.2.1-3.el7 python-kitchen.noarch 0:1.1.1-5.el7 Dependency Updated: libxml2.x86_64 0:2.9.1-6.el7_9.6 Complete!
#3.设置镜像的仓库 #这里使用阿里云的镜像地址 http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo [root@iZ2zec2gz7h1jgw8klihsnZ /]# yum-config-manager \ > --add-repo \ > http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo Loaded plugins: fastestmirror adding repo from: http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo grabbing file http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo to /etc/yum.repos.d/docker-ce.repo repo saved to /etc/yum.repos.d/docker-ce.repo
#清空yum索引 [root@iZ2zec2gz7h1jgw8klihsnZ /]# yum makecache fast Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile base | 3.6 kB 00:00:00 docker-ce-stable | 3.5 kB 00:00:00 epel | 4.7 kB 00:00:00 extras | 2.9 kB 00:00:00 updates | 2.9 kB 00:00:00 (1/2): docker-ce-stable/7/x86_64/updateinfo | 55 B 00:00:00 (2/2): docker-ce-stable/7/x86_64/primary_db | 76 kB 00:00:00 Metadata Cache Created [root@iZ2zec2gz7h1jgw8klihsnZ /]#
#4.安装Docker引擎 #docker-ce 社区版 ee 企业版
[root@iZ2zec2gz7h1jgw8klihsnZ /]# yum install docker-ce docker-ce-cli containerd.io docker-compose-plugin
#5.启动Docker [root@iZ2zec2gz7h1jgw8klihsnZ /]# systemctl start docker
#使用docker version 测试是否安装成功 [root@iZ2zec2gz7h1jgw8klihsnZ /]# docker version Client: Docker Engine - Community Version: 20.10.15 API version: 1.41 Go version: go1.17.9 Git commit: fd82621 Built: Thu May 5 13:16:58 2022 OS/Arch: linux/amd64 Context: default Experimental: true Server: Docker Engine - Community Engine: Version: 20.10.15 API version: 1.41 (minimum version 1.12) Go version: go1.17.9 Git commit: 4433bf6 Built: Thu May 5 13:15:18 2022 OS/Arch: linux/amd64 Experimental: false containerd: Version: 1.6.4 GitCommit: 212e8b6fa2f44b9c21b2798135fc6fb7c53efc16 runc: Version: 1.1.1 GitCommit: v1.1.1-0-g52de29d docker-init: Version: 0.19.0 GitCommit: de40ad0
#7.docker run hello-world
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pull complete
Digest: sha256:10d7d58d5ebd2a652f4d93fdd86da8f265f5318c6a73cc5b6a9798ff6d2b2e67
Status: Downloaded newer image for hello-world:latest
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/
#8.查看下载的这个 hello-world镜像 [root@iZ2zec2gz7h1jgw8klihsnZ /]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE hello-world latest feb5d9fea6a5 7 months ago 13.3kB
如何卸载Docker?
#1.Uninstall the Docker Engine, CLI, Containerd, and Docker Compose packages: yum remove docker-ce docker-ce-cli containerd.io
#2.Images, containers, volumes, or customized configuration files on your host are not automatically removed. To delete all images, containers, and volumes:
#删除docker资源 /var/lib/ docker默认资源路径 rm -rf /var/lib/docker rm -rf /var/lib/containerd
如何设置内部阿里云镜像加速?
1.找到阿里云的镜像加速器页面

2.配置竞相加速器
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF' { "registry-mirrors": ["https://ct2e6f86.mirror.aliyuncs.com"] } EOF
sudo systemctl daemon-reload
sudo systemctl restart docker
Docker run的流程图

底层原理:Docker是怎么工作的?
Docker是一个Client-Server结构的系统,Docker的守护进程运行在主机,通过Socket从客户端访问!
DockerServer接收到Docker-Client的指令,就会执行这个命令!

Docker为什么比虚拟机快?
1.Docker有着比虚拟机更少的抽象层。

2.Docker利用的是宿主机的内核,而VM需要的是Guest OS.
所以说,新建一个容器的时候,docker不需要虚拟机一样重新加载一个操作系统内核,避免引导。虚拟机是加载Guest OS,分钟级别;而docker是利用宿主机的操作系统,省略了复杂的过程,秒级!

Docker命令
帮助命令
#docker version 显示docker版本信息 [root@iZ2zec2gz7h1jgw8klihsnZ /]# docker version
Client: Docker Engine - Community
Version: 20.10.15
API version: 1.41
Go version: go1.17.9
Git commit: fd82621
Built: Thu May 5 13:16:58 2022
OS/Arch: linux/amd64
Context: default
Experimental: true
Server: Docker Engine - Community
Engine:
Version: 20.10.15
API version: 1.41 (minimum version 1.12)
Go version: go1.17.9
Git commit: 4433bf6
Built: Thu May 5 13:15:18 2022
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.6.4
GitCommit: 212e8b6fa2f44b9c21b2798135fc6fb7c53efc16
runc:
Version: 1.1.1
GitCommit: v1.1.1-0-g52de29d
docker-init:
Version: 0.19.0
GitCommit: de40ad0
#docker info 显示Docker的系统信息,包括镜像和容器的数量
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker info
Client:
Context: default
Debug Mode: false
Plugins:
app: Docker App (Docker Inc., v0.9.1-beta3)
buildx: Docker Buildx (Docker Inc., v0.8.2-docker)
compose: Docker Compose (Docker Inc., v2.5.0)
scan: Docker Scan (Docker Inc., v0.17.0)
Server:
Containers: 1
Running: 0
Paused: 0
Stopped: 1
Images: 1
Server Version: 20.10.15
Storage Driver: overlay2
Backing Filesystem: extfs
Supports d_type: true
Native Overlay Diff: true
userxattr: false
Logging Driver: json-file
Cgroup Driver: cgroupfs
Cgroup Version: 1
Plugins:
Volume: local
Network: bridge host ipvlan macvlan null overlay
Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
Swarm: inactive
Runtimes: io.containerd.runtime.v1.linux runc io.containerd.runc.v2
Default Runtime: runc
Init Binary: docker-init
containerd version: 212e8b6fa2f44b9c21b2798135fc6fb7c53efc16
runc version: v1.1.1-0-g52de29d
init version: de40ad0
Security Options:
seccomp
Profile: default
Kernel Version: 3.10.0-1062.18.1.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 1.795GiB
Name: iZ2zec2gz7h1jgw8klihsnZ
ID: T2TL:C3VA:3VFE:KVI6:S4CL:X4HL:NNWR:GLBH:NDIC:Y35B:GGDE:TQVG
Docker Root Dir: /var/lib/docker
Debug Mode: false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
127.0.0.0/8
Registry Mirrors:
https://ct2e6f86.mirror.aliyuncs.com/
Live Restore Enabled: false
#docker --help 帮助命令
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker --help
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
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.8.2-docker)
compose* Docker Compose (Docker Inc., v2.5.0)
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.17.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.
To get more help with docker, check out our guides at https://docs.docker.com/go/guides/
镜像命令
#docker images 查看本地主机上的镜像
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker images --help
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
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest feb5d9fea6a5 7 months ago 13.3kB
#解释
#REPOSITORY 镜像的仓库源
#TAG 镜像的标签
#IMAGE ID 镜像的id
#CREATED 镜像的创建时间
#SIZE 镜像的大小
#docker search命令 搜索镜像
[root@iZ2zec2gz7h1jgw8klihsnZ /]# 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
#--filter=STARS=3000 这时候就会搜索出STARS>3000的候选项
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker search mysql
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 12521 [OK]
mariadb MariaDB Server is a high performing open sou… 4816 [OK]
mysql/mysql-server Optimized MySQL Server Docker images. Create… 925 [OK]
#docker pull 下载镜像 docker pull 镜像名 [:tag]
[root@iZ2zec2gz7h1jgw8klihsnZ /]# 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
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker pull mysql
Using default tag: latest#如果不写tag,默认就是latest 最新版 docker pull mysql 等价于 docker pull mysql:latest
latest: Pulling from library/mysql
72a69066d2fe: Pull complete #分层下载,docker image的核心 联合文件系统
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 #真实地址
[root@iZ2zec2gz7h1jgw8klihsnZ /]#
#############################################
#制定版本下载
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker pull mysql:5.7
5.7: Pulling from library/mysql
72a69066d2fe: Already exists
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 删除镜像
[root@iZ2zec2gz7h1jgw8klihsnZ /]# 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
#指定ID删除 docker rmi -f 容器id
#删除多个容器 docker rmi -f 容器id1 容器id2 ...
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker rmi -f 3218b38490ce
Untagged: mysql:latest
Untagged: mysql@sha256:e9027fe4d91c0153429607251656806cc784e914937271037f7738bd5b8e7709
Deleted: sha256:3218b38490cec8d31976a40b92e09d61377359eab878db49f025e5d464367f3b
Deleted: sha256:aa81ca46575069829fe1b3c654d9e8feb43b4373932159fe2cad1ac13524a2f5
Deleted: sha256:0558823b9fbe967ea6d7174999be3cc9250b3423036370dc1a6888168cbd224d
Deleted: sha256:a46013db1d31231a0e1bac7eeda5ad4786dea0b1773927b45f92ea352a6d7ff9
Deleted: sha256:af161a47bb22852e9e3caf39f1dcd590b64bb8fae54315f9c2e7dc35b025e4e3
Deleted: sha256:feff1495e6982a7e91edc59b96ea74fd80e03674d92c7ec8a502b417268822ff
[root@iZ2zec2gz7h1jgw8klihsnZ /]#
#回调删除
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker rmi $(docker images -qa)
Untagged: mysql:5.7
Untagged: mysql@sha256:f2ad209efe9c67104167fc609cca6973c8422939491c9345270175a300419f94
Deleted: sha256:c20987f18b130f9d144c9828df630417e2a9523148930dc3963e9d0dab302a76
Deleted: sha256:6567396b065ee734fb2dbb80c8923324a778426dfd01969f091f1ab2d52c7989
Deleted: sha256:0910f12649d514b471f1583a16f672ab67e3d29d9833a15dc2df50dd5536e40f
Deleted: sha256:6682af2fb40555c448b84711c7302d0f86fc716bbe9c7dc7dbd739ef9d757150
Deleted: sha256:5c062c3ac20f576d24454e74781511a5f96739f289edaadf2de934d06e910b92
Deleted: sha256:8805862fcb6ef9deb32d4218e9e6377f35fb351a8be7abafdf1da358b2b287ba
Deleted: sha256:872d2f24c4c64a6795e86958fde075a273c35c82815f0a5025cce41edfef50c7
Deleted: sha256:6fdb3143b79e1be7181d32748dd9d4a845056dfe16ee4c827410e0edef5ad3da
Deleted: sha256:b0527c827c82a8f8f37f706fcb86c420819bb7d707a8de7b664b9ca491c96838
Deleted: sha256:75147f61f29796d6528486d8b1f9fb5d122709ea35620f8ffcea0e0ad2ab0cd0
Deleted: sha256:2938c71ddf01643685879bf182b626f0a53b1356138ef73c40496182e84548aa
Deleted: sha256:ad6b69b549193f81b039a1d478bc896f6e460c77c1849a4374ab95f9a3d2cea2
Error response from daemon: conflict: unable to delete feb5d9fea6a5 (must be forced) - image is being used by stopped container 8b4dd872b6e7
容器命令
我们有了镜像才可以常见容器,linux,下载一个linux镜像来测试学习
#下载一个centos镜像
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker search centos
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
centos The official build of CentOS. 7133 [OK]
centos/systemd systemd enabled base container. 108 [OK]
centos/mysql-57-centos7 MySQL 5.7 SQL database server 94
centos/postgresql-96-centos7 PostgreSQL is an advanced Object-Relational … 45
centos/httpd-24-centos7 Platform for running Apache httpd 2.4 or bui… 44
centos/php-56-centos7 Platform for building and running PHP 5.6 ap… 34
centos/mysql-56-centos7 MySQL 5.6 SQL database server 22
kasmweb/centos-7-desktop CentOS 7 desktop for Kasm Workspaces 19
centos/postgresql-10-centos7 PostgreSQL is an advanced Object-Relational … 19
centos/nginx-112-centos7 Platform for running nginx 1.12 or building … 16
centos/nginx-18-centos7 Platform for running nginx 1.8 or building n… 14
centos/mariadb-101-centos7 MariaDB 10.1 SQL database server 13
centos/mongodb-36-centos7 MongoDB NoSQL database server 8
centos/mariadb-102-centos7 MariaDB 10.2 SQL database server 6
centos/redis-32-centos7 Redis in-memory data structure store, used a… 6
kasmweb/core-centos-7 CentOS 7 base image for Kasm Workspaces 3
centos/ruby-25-centos7 Platform for building and running Ruby 2.5 a… 3
continuumio/centos5_gcc5_base 3
centos/mongodb-34-centos7 MongoDB NoSQL database server 3
ibmcom/fhe-toolkit-centos The IBM Fully Homomorphic Encryption (FHE) T… 0
ibmcom/fhe-toolkit-centos-amd64 The IBM Fully Homomorphic Encryption (FHE) T… 0
datadog/centos-i386 0
bitnami/centos-extras-base 0
bitnami/centos-base-buildpack Centos base compilation image 0 [OK]
centos/nginx-110-centos7 Platform for running nginx 1.10 or building … 0
[root@iZ2zec2gz7h1jgw8klihsnZ /]# doucker pull centos
-bash: doucker: command not found
[root@iZ2zec2gz7h1jgw8klihsnZ /]# douker pull centos
-bash: douker: command not found
[root@iZ2zec2gz7h1jgw8klihsnZ /]# 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
#docker run 新建容器启动
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker run --help
Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
#常见参数说明
#--name="容器名" 容器名字 tomcat01 tomcat02,用来区分容器
#-d 后台运行
#-it 使用交互方式运行,进入容器查看内容
#-p 制定容器端口 -p 8080:8080
#-p使用方式
#-p ip:主机端口:容器端口
#-p 主机端口:容器端口(常用)
#-p 容器端口
#-P 随机制定端口
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
#################################################################################
#测试docker run 命令的使用
[root@iZ2zec2gz7h1jgw8klihsnZ /]#
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker run -it centos /bin/bash #启动并进入容器
[root@4cc85a317196 /]# ls #查看容器内的centos,基础版本,很多命令都是不完善的
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
[root@4cc85a317196 /]# exit #从容器中退回主机
exit
[root@iZ2zec2gz7h1jgw8klihsnZ /]#
#docker ps查看运行中的容器
# 列出当前正在运行的容器
#-a 列出当前正在运行的容器,带出历史运行过的容器
#-n=? 显示最近创建的容器
#-q 只显示容器的ID
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps #列出当前正在运行中的容器
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps -a #列出
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4cc85a317196 centos "/bin/bash" 3 minutes ago Exited (0) About a minute ago ecstatic_robinson
8b4dd872b6e7 hello-world "/hello" 2 hours ago Exited (0) 2 hours ago admiring_gould
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps -aq
4cc85a317196
8b4dd872b6e7
#退出容器相关命令
exit #直接容器停止并退出
ctrl+p+q #容器不停止退出
#删除容器
docker rm 容器id #删除指定容器 不能删除正在运行中的容器, docker rm -f 容器id强制删除容器
docker rm -f $(docker ps -aq) #删除所有容器
docker ps -a|xargs docker rm #通过管道符删除所有容器
#启动和停止容器的操作
docker start 容器id #启动容器
docker restart 容器id #重启容器
docker stop 容器id #停止当前运行容器
docker kill 容器id #强制停止当前容器
#后台启动容器
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker run -d --name="centos02" centos
1a0f5a321118bd793f70fabdd868e2a543ba18ee83838fa766a525a7869d15a8
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1a0f5a321118 centos "/bin/bash" 6 seconds ago Exited (0) 5 seconds ago centos02
8be72caaa4a7 centos "/bin/bash" 8 minutes ago Up 8 minutes centos01
4cc85a317196 centos "/bin/bash" 20 minutes ago Up About a minute ecstatic_robinson
8b4dd872b6e7 hello-world "/hello" 2 hours ago Exited (0) 2 hours ago admiring_gould
#########问题:docker ps 发现启动的命名为"centos02"的容器状态停止了
#########常见的坑:容器使用后台运行,就必须要有一个前台进程,docker发现该容器没有应用,就会自动停止
#########Nginx,容器启动后,发现自己没有提供服务,就会立刻停止(它自己就会认为没有程序了)
#docker logs 查看日志命令
[root@iZ2zec2gz7h1jgw8klihsnZ /]# 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)
docker logs -f -t 容器id, 没有日志
#自己编写一个shell脚本
root@iZ2zec2gz7h1jgw8klihsnZ /]# docker logs -f -t --tail=10 87c4f1ebc327 #--tail=number 要显示的日志条数
2022-05-06T11:22:38.879103869Z kuangshen
2022-05-06T11:22:39.881477695Z kuangshen
2022-05-06T11:22:40.886896828Z kuangshen
2022-05-06T11:22:41.888957987Z kuangshen
2022-05-06T11:22:42.891040169Z kuangshen
2022-05-06T11:22:43.893141573Z kuangshen
2022-05-06T11:22:44.895206262Z kuangshen
2022-05-06T11:22:45.897327442Z kuangs
#docker top 容器id 查看容器中的进程信息
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
87c4f1ebc327 centos "/bin/sh -c 'while t…" 3 minutes ago Up 3 minutes sad_babbage
8be72caaa4a7 centos "/bin/bash" About an hour ago Up About an hour centos01
4cc85a317196 centos "/bin/bash" About an hour ago Up 57 minutes ecstatic_robinson
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker top 87c4f1ebc327
UID PID PPID C STIME TTY TIME CMD
root 18172 18153 0 19:21 ? 00:00:00 /bin/sh -c while true;do echo kuangshen;sleep 1;done
root 18533 18172 0 19:25 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
[root@iZ2zec2gz7h1jgw8klihsnZ /]#
#docker inspect 容器id #查看镜像容器的元数据
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker inspect 87c4f1ebc327 [ { "Id": "87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8", "Created": "2022-05-06T11:21:30.439030234Z", "Path": "/bin/sh", "Args": [ "-c", "while true;do echo kuangshen;sleep 1;done" ], "State": { "Status": "running", "Running": true, "Paused": false, "Restarting": false, "OOMKilled": false, "Dead": false, "Pid": 18172, "ExitCode": 0, "Error": "", "StartedAt": "2022-05-06T11:21:30.731601995Z", "FinishedAt": "0001-01-01T00:00:00Z" }, "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6", "ResolvConfPath": "/var/lib/docker/containers/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8/resolv.conf", "HostnamePath": "/var/lib/docker/containers/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8/hostname", "HostsPath": "/var/lib/docker/containers/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8/hosts", "LogPath": "/var/lib/docker/containers/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8-json.log", "Name": "/sad_babbage", "RestartCount": 0, "Driver": "overlay2", "Platform": "linux", "MountLabel": "", "ProcessLabel": "", "AppArmorProfile": "", "ExecIDs": null, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LogConfig": { "Type": "json-file", "Config": {} }, "NetworkMode": "default", "PortBindings": {}, "RestartPolicy": { "Name": "no", "MaximumRetryCount": 0 }, "AutoRemove": false, "VolumeDriver": "", "VolumesFrom": null, "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", "ConsoleSize": [ 0, 0 ], "Isolation": "", "CpuShares": 0, "Memory": 0, "NanoCpus": 0, "CgroupParent": "", "BlkioWeight": 0, "BlkioWeightDevice": [], "BlkioDeviceReadBps": null, "BlkioDeviceWriteBps": null, "BlkioDeviceReadIOps": null, "BlkioDeviceWriteIOps": null, "CpuPeriod": 0, "CpuQuota": 0, "CpuRealtimePeriod": 0, "CpuRealtimeRuntime": 0, "CpusetCpus": "", "CpusetMems": "", "Devices": [], "DeviceCgroupRules": null, "DeviceRequests": null, "KernelMemory": 0, "KernelMemoryTCP": 0, "MemoryReservation": 0, "MemorySwap": 0, "MemorySwappiness": null, "OomKillDisable": false, "PidsLimit": null, "Ulimits": null, "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" ], "ReadonlyPaths": [ "/proc/bus", "/proc/fs", "/proc/irq", "/proc/sys", "/proc/sysrq-trigger" ] }, "GraphDriver": { "Data": { "LowerDir": "/var/lib/docker/overlay2/9b9a635e925c8aa964088742fd2928d071db52a0fca036846b4e6ce404096bdb-init/diff:/var/lib/docker/overlay2/f0b92d162490bac978b459ad6cc2a7e24cf8a2b60c0f10b0e9c66d0638936237/diff", "MergedDir": "/var/lib/docker/overlay2/9b9a635e925c8aa964088742fd2928d071db52a0fca036846b4e6ce404096bdb/merged", "UpperDir": "/var/lib/docker/overlay2/9b9a635e925c8aa964088742fd2928d071db52a0fca036846b4e6ce404096bdb/diff", "WorkDir": "/var/lib/docker/overlay2/9b9a635e925c8aa964088742fd2928d071db52a0fca036846b4e6ce404096bdb/work" }, "Name": "overlay2" }, "Mounts": [], "Config": { "Hostname": "87c4f1ebc327", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd": [ "/bin/sh", "-c", "while true;do echo kuangshen;sleep 1;done" ], "Image": "centos", "Volumes": null, "WorkingDir": "", "Entrypoint": null, "OnBuild": null, "Labels": { "org.label-schema.build-date": "20210915", "org.label-schema.license": "GPLv2", "org.label-schema.name": "CentOS Base Image", "org.label-schema.schema-version": "1.0", "org.label-schema.vendor": "CentOS" } }, "NetworkSettings": { "Bridge": "", "SandboxID": "3f9ef183276fa2747b7fd8abd5b9eccfc62bd17e7e2ac2036f79625a395bee89", "HairpinMode": false, "LinkLocalIPv6Address": "", "LinkLocalIPv6PrefixLen": 0, "Ports": {}, "SandboxKey": "/var/run/docker/netns/3f9ef183276f", "SecondaryIPAddresses": null, "SecondaryIPv6Addresses": null, "EndpointID": "ed5f048fa928944e057d1c1b068f89253ace616e56b9dc4a9aada0916c8c959c", "Gateway": "172.17.0.1", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "IPAddress": "172.17.0.4", "IPPrefixLen": 16, "IPv6Gateway": "", "MacAddress": "02:42:ac:11:00:04", "Networks": { "bridge": { "IPAMConfig": null, "Links": null, "Aliases": null, "NetworkID": "feb3d1ca8d81153ef6a23103a75495fc92bc2776d479880673eafebf84c46e11", "EndpointID": "ed5f048fa928944e057d1c1b068f89253ace616e56b9dc4a9aada0916c8c959c", "Gateway": "172.17.0.1", "IPAddress": "172.17.0.4", "IPPrefixLen": 16, "IPv6Gateway": "", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "MacAddress": "02:42:ac:11:00:04", "DriverOpts": null } } } } ]
#进入当前正在运行的容器
#方式一
#docker exec -it 容器id bashshell #我们通常容器都是使用后台方式进行的,需要进入容器,修改一些配置 #命令 root@iZ2zec2gz7h1jgw8klihsnZ /]# docker exec -it 8be72caaa4a7 /bin/bash [root@8be72caaa4a7 /]# ls bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var [root@8be72caaa4a7 /]#
#方式二
#docker attach 容器id
#正在执行当前的代码。。。
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker attach --help
Usage: docker attach [OPTIONS] CONTAINER
Attach local standard input, output, and error streams to a running container
Options:
--detach-keys string Override the key sequence for detaching a container
--no-stdin Do not attach STDIN
--sig-proxy Proxy all received signals to the process (default true)
#####################################
#docker exec 和 docker attach的区别
#docker exec #进入容器后开启一个新的终端,可以在里面操作(常用)
#docker attach #进入容器后正在执行的终端,不会启动新的进程!
#docker cp 容器id:/目录/文件 主机目录 容器内容从容器拷贝到主机上
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker cp 4cc85a317196:/home/tmp_cp.java /home
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# cd /home
[root@iZ2zec2gz7h1jgw8klihsnZ home]# ls
tmp_cp.java wgy
[root@iZ2zec2gz7h1jgw8klihsnZ home]#
###################################
#docker是一个手动过程,为了我们使用 -v 卷的技术,可以实现,自动同步 /home /home
操作命令总结

Docker安装Nginx
#Docker安装Nginx
#步骤1 搜索镜像 docker search nginx
#步骤2 下载镜像 docker pull nginx
#步骤3 查看镜像 docker images
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker run -d --name nginx01 -p:3344:80 nginx #后台运行nginx容器
45114e9800fba66d6c9c5e05180014a3a901e9df19f3bb393406cd104038ef48
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
45114e9800fb nginx "/docker-entrypoint.…" 4 seconds ago Up 4 seconds 0.0.0.0:3344->80/tcp nginx01
87c4f1ebc327 centos "/bin/sh -c 'while t…" 20 hours ago Up 20 hours sad_babbage
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# curl localhost:3344 # curl 是一种命令行工具,作用是发出网络请求,然后获取数据,显示在"标准输出"(stdout)上面。它支持多种协议,下面列举其常用功能。
<!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>
此处需要讲解一下 -p 宿主机端口:容器端口 的作用
用户无法直接访问容器端口,我们使用-p,来将宿主机端口与容器端口进行绑定(打通端口),从而用户可以通过宿主机端口访问到容器端口,进而访问容器端口相应的服务。

此时可以通过宿主机的端口:ip访问nginx容器启动的nginx服务的欢迎页面

#进入到nginx容器内部
root@8597a6f04b0d:/usr/sbin# cd /etc/nginx
root@8597a6f04b0d:/etc/nginx# ls
conf.d fastcgi_params mime.types modules nginx.conf scgi_params uwsgi_params
root@8597a6f04b0d:/etc/nginx# cat nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
问题:每次改动nginx配置文件,都需要进入容器内部?十分地麻烦,我要是可以在容器外部提供一个映射路径,达到在容器外部修改文件,容器内部就可以自动修改的目的。
Docker部署Tomcat
dockerHub官方提供的安装命令
docker run -it --rm tomcat:9.0
#我们之前的启动都是后台,停止了容器之后,容器还是可以看到 docker run -it --rm 一般用来测试,运行完就删除
学习过程中部署Docker的安装命令
#下载tomcat镜像 docker pull tomcat
#运行tomcat容器
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker run -d -p 3345:8080 --name tomcat01 tomcat
405e34e4755157541f480adeb758c76504266c14cd63ccc2034e762ba5dc616c
#进入到tomcat容器中
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker exec -it 405e34e47551 /bin/bash
root@405e34e47551:/usr/local/tomcat# whereis tomcat
tomcat: /usr/local/tomcat
root@405e34e47551:/usr/local/tomcat# ls
BUILDING.txt LICENSE README.md RUNNING.txt conf logs temp webapps.dist
CONTRIBUTING.md NOTICE RELEASE-NOTES bin lib native-jni-lib webapps work
root@405e34e47551:/usr/local/tomcat# cd webapps #此时发现webapps目录下为空
root@405e34e47551:/usr/local/tomcat/webapps#
####发现问题 webapps目录下什么都没有,阿里云镜像默认是最小镜像,所有不必要的镜像都剔除掉
####保证最小可运行的环境
以后要部署项目,每次都要进入容器是不是十分麻烦?要是可以在容器外部提供一个映射路径,webapps,在外部放置项目就自动同步到内部就好了!
部署es+kibana
#es 暴露的端口非常多
#es 十分的耗内存
#es 的数据一般都放置到安全目录,
#--net somework 网络配置
#docker run -d --name elasticsearch --net somenetwork -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:tag
#启动docker容器服务
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2
Unable to find image 'elasticsearch:7.6.2' locally
7.6.2: Pulling from library/elasticsearch
ab5ef0e58194: Pull complete
c4d1ca5c8a25: Pull complete
941a3cc8e7b8: Pull complete
43ec483d9618: Pull complete
c486fd200684: Pull complete
1b960df074b2: Pull complete
1719d48d6823: Pull complete
Digest: sha256:1b09dbd93085a1e7bca34830e77d2981521a7210e11f11eda997add1c12711fa
Status: Downloaded newer image for elasticsearch:7.6.2
5bed8e09f3e4644ac7f99027810c65d521325bd99a57dd8edb7836f6cbd3d6d1
#docker status 查看cpu的状态
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker ps -aq
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
ec208095a057 elasticsearch 98.01% 1.244GiB / 1.795GiB 69.34% 0B / 0B 207MB / 246kB 26
#关闭当前es容器,增加内存限制,修改配置文件, -e 环境配置修改
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# curl localhost:9200
{
"name" : "71773db7f220",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "3CayxfTES_mRBzO-fDlurw",
"version" : {
"number" : "7.6.2",
"build_flavor" : "default",
"build_type" : "docker",
"build_hash" : "ef48eb35cf30adf4db14086e8aabd07ef6fb113f",
"build_date" : "2020-03-26T06:34:37.794943Z",
"build_snapshot" : false,
"lucene_version" : "8.4.0",
"minimum_wire_compatibility_version" : "6.8.0",
"minimum_index_compatibility_version" : "6.0.0-beta1"
},
"tagline" : "You Know, for Search"
}
es和kibana交互原理

可视化
portainer
Docker图形化管理工具,提供一个后台面板供我们操作!
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker run -d -p 3346:9000 --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer Unable to find image 'portainer/portainer:latest' locally latest: Pulling from portainer/portainer 94cfa856b2b1: Pull complete 49d59ee0881a: Pull complete a2300fd28637: Pull complete Digest: sha256:fb45b43738646048a0a0cc74fcee2865b69efde857e710126084ee5de9be0f3f Status: Downloaded newer image for portainer/portainer:latest 9f66596e5679ff98d0ce8ae51e36dc35d5dcbe489c6750e6f68471217cd55adb
Rancher(CI/CD再用)
Docker镜像
镜像是什么?
镜像是一个轻量级,可执行的独立软件包,用来打包软件运行环境和基于运行环境开发的软件,它包含某个软件所需的所有内容,包含代码,运行时,库,环境变量和配置文件。
所有的应用,直接打包成为一个docker镜像,就可以直接跑起来!
如何得到镜像?
- 从远程仓库下载
- 朋友拷贝给你
- 自己制作一个镜像DockerFile
镜像加载原理
Docker是一个轻量级的、可执行的独立软件包,将一个应用程序和环境打包成为一个文件包,这个打包好的文件包就是Docker镜像。只有通过镜像文件才能生成容器实例。。镜像文件是分层的,底层采用联合文件系统来实现。
联合文件系统(UnionFS)
联合文件系统是一个轻量级、高性能的文件系统;他支持对文件系统的修改作为一次提交来一层层叠加;同时可以将不同的目录挂载到同一个文件系统下.UnionFs是Docker镜像的基础。可以通过分层来继承基础镜像,提高文件的复用。


Docker镜像加载原理
bootfs(boot file system) 主要包含bootloader和kernel, bpotloader 主要是引导加载kernel,当我们加载镜像的时候,会通过bootloader加载kernal,Docker镜像最底层是bootfs,当boot加载完成后整个kernal内核都在内存中了,bootfs也就可以卸载,值得注意的是,bootfs是被所有镜像共用的,许多镜像images都是在base image(rootfs)基础上叠加的。
rootfs (root file system),在bootfs之 上.包含的就是典型Linux系统中的/dev, /proc, /bin, /etc等标准目录和文件。rootfs就是 各种不同的操作系统发行版,比如Ubuntu, Centos等等 。
分层原理介绍
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker pull redis Using default tag: latest latest: Pulling from library/redis a2abf6c4d29d: Already exists c7a4e4382001: Pull complete 4044b9ba67c9: Pull complete c8388a79482f: Pull complete 413c8bb60be2: Pull complete 1abfd3011519: Pull complete Digest: sha256:db485f2e245b5b3329fdc7eff4eb00f913e09d8feb9ca720788059fdc2ed8339 Status: Downloaded newer image for redis:latest docker.io/library/redis:latest [root@iZ2zec2gz7h1jgw8klihsnZ ~]#
#docker inspect redis 看到配置文件中有一个Layers,里面包含
"Layers": [ "sha256:2edcec3590a4ec7f40cf0743c15d78fb39d8326bc029073b41ef9727da6c851f", "sha256:9b24afeb7c2f21e50a686ead025823cd2c6e9730c013ca77ad5f115c079b57cb", "sha256:4b8e2801e0f956a4220c32e2c8b0a590e6f9bd2420ec65453685246b82766ea1", "sha256:529cdb636f61e95ab91a62a51526a84fd7314d6aab0d414040796150b4522372", "sha256:9975392591f2777d6bf4d9919ad1b2c9afa12f9a9b4d260f45025ec3cc9b18ed", "sha256:8e5669d8329116b8444b9bbb1663dda568ede12d3dbcce950199b582f6e94952" ]
特点
Docker镜像都是只读的,当容器启动时,一个新的可写层被加载到镜像的顶部!
这一层是我们经常说的容器层,容器之下的都叫做镜像层

如何提交(Commit)一个镜像?
-
容器数据卷
-
DockerFile
-
Docker网络原理
-
IDEA整合Docker
-
Docker Compose
-
Docker Swarm
-
CI\CD Jenkins

浙公网安备 33010602011771号