https://docs.docker.com/
Docker provides a way to run applications securely isolated in a container, packaged with all its dependencies and libraries.
容器认识
首先想一下Windows环境下,我们安装虚拟机,比如有VM1、VM2、VM3等,这些都是Linux操作系统系统;而Docker是基于CentOS7.x,再在上面部署docker1、docker2、docker3
注意:必须是7.X的版本,一个Linux操作系统可以装很多的镜像实例
- image,镜像(模板文件),就相当于装VM虚拟机的iso文件
- container,容器,以进程形式运行 ,是运行的状态,正常一个docker里面只允许一个进程,底层还是以进程的形式运行
安装(阿里云)
https://docs.docker.com/engine/install/centos/
我们这里是基于阿里云Centos7.2的环境,官网上选择Install Docker Engine on CentOS
环境准备
- CentOS 64位必须是7.1及更高版本x86_64
[root@hadoop001 ~]# clear
[root@hadoop001 ~]# cat /etc/centos-release
CentOS Linux release 7.2.1511 (Core)
- 使用存储驱动程序overlay2或devicemapper(direct-lvm生产模式)
- 在Docker Hub上找到您的Docker EE存储库的URL
- 卸载旧版本的Docker
$ sudo yum remove docker \
docker-client \
docker-client-latest \
docker-common \
docker-latest \
docker-latest-logrotate \
docker-logrotate \
docker-engine
- 从中删除旧的Docker存储库/etc/yum.repos.d/
为了保证环境干净,先执行以下几步
//Docker都是基于rpm包或者yum源安装的
[root@hadoop001 yum.repos.d]# pwd
/etc/yum.repos.d
[root@hadoop001 yum.repos.d]# rpm -qa|grep docker
[root@hadoop001 yum.repos.d]#
//如果存在的话,就用rpm -e命令去卸载,我们这里没有就下一步
[root@hadoop001 yum.repos.d]# rpm -qa|grep docker
[root@hadoop001 yum.repos.d]# ll /var/lib/docker/
[root@hadoop001 yum.repos.d]# rm -rf /var/lib/docker/* 这一步一定不要忘
[root@hadoop001 yum.repos.d]# rm /etc/yum.repos.d/docker*.repo
安装依赖包
[root@hadoop001 ~]# yum install -y yum-utils device-mapper-persistent-data lvm2
# 添加稳定的仓库,因为要使用yum源安装,正常的Centos操作系统里面是没有配置Docker的镜像仓库
[root@hadoop001 ~]# cd /etc/yum.repos.d/
[root@hadoop001 yum.repos.d]# ll //正常的里面是没有Docker源的
total 8
-rw-r--r-- 1 root root 675 Apr 19 11:58 CentOS-Base.repo
-rw-r--r-- 1 root root 230 Apr 19 11:58 epel.repo
[root@hadoop001 yum.repos.d]# yum-config-manager \
--add-repo \
https://download.docker.com/linux/centos/docker-ce.repo
Loaded plugins: fastestmirror
adding repo from: https://download.docker.com/linux/centos/docker-ce.repo
grabbing file https://download.docker.com/linux/centos/docker-ce.repo to /etc/yum.repos.d/docker-ce.repo
repo saved to /etc/yum.repos.d/docker-ce.repo //下载一个文件来保存到docker-ce.repo的文件中
[root@hadoop001 yum.repos.d]# ll
total 12
-rw-r--r-- 1 root root 675 Apr 19 11:58 CentOS-Base.repo
-rw-r--r-- 1 root root 2424 Oct 19 2019 docker-ce.repo
-rw-r--r-- 1 root root 230 Apr 19 11:58 epel.repo
[root@hadoop001 yum.repos.d]# cat docker-ce.repo
[docker-ce-stable]
name=Docker CE Stable - $basearch
baseurl=https://download.docker.com/linux/centos/7/$basearch/stable
enabled=1
gpgcheck=1
gpgkey=https://download.docker.com/linux/centos/gpg
[docker-ce-stable-debuginfo]
name=Docker CE Stable - Debuginfo $basearch
baseurl=https://download.docker.com/linux/centos/7/debug-$basearch/stable
enabled=0
gpgcheck=1
gpgkey=https://download.docker.com/linux/centos/gpg
[docker-ce-stable-source]
name=Docker CE Stable - Sources
baseurl=https://download.docker.com/linux/centos/7/source/stable
enabled=0
gpgcheck=1
gpgkey=https://download.docker.com/linux/centos/gpg
[docker-ce-edge]
name=Docker CE Edge - $basearch
baseurl=https://download.docker.com/linux/centos/7/$basearch/edge
enabled=0
gpgcheck=1
gpgkey=https://download.docker.com/linux/centos/gpg
[docker-ce-edge-debuginfo]
name=Docker CE Edge - Debuginfo $basearch
baseurl=https://download.docker.com/linux/centos/7/debug-$basearch/edge
enabled=0
gpgcheck=1
gpgkey=https://download.docker.com/linux/centos/gpg
[docker-ce-edge-source]
name=Docker CE Edge - Sources
baseurl=https://download.docker.com/linux/centos/7/source/edge
enabled=0
gpgcheck=1
gpgkey=https://download.docker.com/linux/centos/gpg
[docker-ce-test]
name=Docker CE Test - $basearch
baseurl=https://download.docker.com/linux/centos/7/$basearch/test
enabled=0
gpgcheck=1
gpgkey=https://download.docker.com/linux/centos/gpg
[docker-ce-test-debuginfo]
name=Docker CE Test - Debuginfo $basearch
baseurl=https://download.docker.com/linux/centos/7/debug-$basearch/test
enabled=0
gpgcheck=1
gpgkey=https://download.docker.com/linux/centos/gpg
[docker-ce-test-source]
name=Docker CE Test - Sources
baseurl=https://download.docker.com/linux/centos/7/source/test
enabled=0
gpgcheck=1
gpgkey=https://download.docker.com/linux/centos/gpg
[docker-ce-nightly]
name=Docker CE Nightly - $basearch
baseurl=https://download.docker.com/linux/centos/7/$basearch/nightly
enabled=0
gpgcheck=1
gpgkey=https://download.docker.com/linux/centos/gpg
[docker-ce-nightly-debuginfo]
name=Docker CE Nightly - Debuginfo $basearch
baseurl=https://download.docker.com/linux/centos/7/debug-$basearch/nightly
enabled=0
gpgcheck=1
gpgkey=https://download.docker.com/linux/centos/gpg
[docker-ce-nightly-source]
name=Docker CE Nightly - Sources
baseurl=https://download.docker.com/linux/centos/7/source/nightly
enabled=0
gpgcheck=1
gpgkey=https://download.docker.com/linux/centos/gpg
//相当于我们在yum源安装的时候,是通过上面地址去下的
# 更新yum包索引
[root@hadoop001 yum.repos.d]# yum makecache fast
# 安装Docker CE
[root@hadoop001 ]# yum -y install docker-ce
# 启动
centos6.x
service mysql start|stop|status
service httpd start|stop|status
centos7.x
service mysql start|stop|status
systemctl start|stop|status mysql
systemctl start mysql httpd .... //一条命令可以启动多个程序,这就是同Centos6.x最大的差别
[root@hadoop001 yum.repos.d]# systemctl start docker
[root@hadoop001 yum.repos.d]# systemctl status docker
● docker.service - Docker Application Container Engine
Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
Active: active (running) since Sun 2020-04-19 12:37:09 CST; 2min 20s ago
Docs: https://docs.docker.com
Main PID: 18841 (dockerd)
Memory: 40.7M
CGroup: /system.slice/docker.service
└─18841 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
Apr 19 12:37:09 hadoop001 dockerd[18841]: time="2020-04-19T12:37:09.429654514+08:00" level=info msg="ccResolverWrapper: sendi...le=grpc
Apr 19 12:37:09 hadoop001 dockerd[18841]: time="2020-04-19T12:37:09.429662595+08:00" level=info msg="ClientConn switching bal...le=grpc
Apr 19 12:37:09 hadoop001 dockerd[18841]: time="2020-04-19T12:37:09.452274411+08:00" level=info msg="Loading containers: start."
Apr 19 12:37:09 hadoop001 dockerd[18841]: time="2020-04-19T12:37:09.543665250+08:00" level=info msg="Default bridge (docker0)...ddress"
Apr 19 12:37:09 hadoop001 dockerd[18841]: time="2020-04-19T12:37:09.582992154+08:00" level=info msg="Loading containers: done."
Apr 19 12:37:09 hadoop001 dockerd[18841]: time="2020-04-19T12:37:09.590157941+08:00" level=warning msg="Not using native diff...verlay2
Apr 19 12:37:09 hadoop001 dockerd[18841]: time="2020-04-19T12:37:09.590294826+08:00" level=info msg="Docker daemon" commit=af...19.03.8
Apr 19 12:37:09 hadoop001 dockerd[18841]: time="2020-04-19T12:37:09.590359827+08:00" level=info msg="Daemon has completed ini...zation"
Apr 19 12:37:09 hadoop001 dockerd[18841]: time="2020-04-19T12:37:09.613059372+08:00" level=info msg="API listen on /var/run/d...r.sock"
Apr 19 12:37:09 hadoop001 systemd[1]: Started Docker Application Container Engine.
Hint: Some lines were ellipsized, use -l to show in full.
[root@hadoop001 yum.repos.d]# which docker
/usr/bin/docker
[root@hadoop001 yum.repos.d]# docker version //是区分客户端以及服务端,另外生产中会存在版本的升级,要记住是分为本身的版本以及API version,并且是go语言写的
Client: Docker Engine - Community
Version: 19.03.8
API version: 1.40
Go version: go1.12.17
Git commit: afacb8b
Built: Wed Mar 11 01:27:04 2020
OS/Arch: linux/amd64
Experimental: false
Server: Docker Engine - Community
Engine:
Version: 19.03.8
API version: 1.40 (minimum version 1.12)
Go version: go1.12.17
Git commit: afacb8b
Built: Wed Mar 11 01:25:42 2020
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.2.13
GitCommit: 7ad184331fa3e55e52b890ea95e65ba581ae3429
runc:
Version: 1.0.0-rc10
GitCommit: dc9208a3303feef5b3839f4323d9beb36df0a9dd
docker-init:
Version: 0.18.0
GitCommit: fec3683
[root@hadoop001 yum.repos.d]#
测试是否安装成功
输入docker命令看是否有命令帮助出来 像下图 那就是安装成功了
[root@hadoop001 yum.repos.d]# docker
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:
builder Manage builds
config Manage Docker configs
container Manage containers
context Manage contexts
engine Manage the docker engine
image Manage images
network Manage networks
node Manage Swarm nodes
plugin Manage plugins
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.
卸载
[root@hadoop001 ~]# systemctl sop docker
[root@hadoop001 ~]# rpm -qa |grep docker
docker-ce-cli-19.03.8-3.el7.x86_64
docker-ce-19.03.8-3.el7.x86_64
//通过rpm -e卸载
[root@hadoop001 ~]# ll /var/lib/docker/
total 48
drwx------ 2 root root 4096 Apr 19 12:37 builder
drwx--x--x 4 root root 4096 Apr 19 12:37 buildkit
drwx------ 2 root root 4096 Apr 19 12:37 containers
drwx------ 3 root root 4096 Apr 19 12:37 image
drwxr-x--- 3 root root 4096 Apr 19 12:37 network
drwx------ 3 root root 4096 Apr 19 12:37 overlay2
drwx------ 4 root root 4096 Apr 19 12:37 plugins
drwx------ 2 root root 4096 Apr 19 12:37 runtimes
drwx------ 2 root root 4096 Apr 19 12:37 swarm
drwx------ 2 root root 4096 Apr 19 12:37 tmp
drwx------ 2 root root 4096 Apr 19 12:37 trust
drwx------ 2 root root 4096 Apr 19 12:37 volumes
[root@hadoop001 ~]# yum.repos.d]# rm -rf /var/lib/docker/*
Docker hub私服
相当于github,大家制作的镜像,开源的可以使用
https://hub.docker.com/search?q=&type=image&image_filter=official
案例一 nginx
[root@hadoop001 ~]# docker search nginx //优先选择第一个官方的
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
nginx Official build of Nginx. 13012 [OK]
jwilder/nginx-proxy Automated Nginx reverse proxy for docker con… 1779 [OK]
richarvey/nginx-php-fpm Container running Nginx + PHP-FPM capable of… 765 [OK]
linuxserver/nginx An Nginx container, brought to you by LinuxS… 105
bitnami/nginx Bitnami nginx Docker Image 82 [OK]
tiangolo/nginx-rtmp Docker image with Nginx using the nginx-rtmp… 69 [OK]
jc21/nginx-proxy-manager Docker container for managing Nginx proxy ho… 53
nginxdemos/hello NGINX webserver that serves a simple page co… 47 [OK]
jlesage/nginx-proxy-manager Docker container for Nginx Proxy Manager 38 [OK]
nginx/unit NGINX Unit is a dynamic web and application … 37
nginx/nginx-ingress NGINX Ingress Controller for Kubernetes 29
privatebin/nginx-fpm-alpine PrivateBin running on an Nginx, php-fpm & Al… 23 [OK]
schmunk42/nginx-redirect A very simple container to redirect HTTP tra… 18 [OK]
nginxinc/nginx-unprivileged Unprivileged NGINX Dockerfiles 13
blacklabelops/nginx Dockerized Nginx Reverse Proxy Server. 13 [OK]
centos/nginx-18-centos7 Platform for running nginx 1.8 or building n… 13
centos/nginx-112-centos7 Platform for running nginx 1.12 or building … 13
raulr/nginx-wordpress Nginx front-end for the official wordpress:f… 12 [OK]
nginx/nginx-prometheus-exporter NGINX Prometheus Exporter 10
sophos/nginx-vts-exporter Simple server that scrapes Nginx vts stats a… 7 [OK]
mailu/nginx Mailu nginx frontend 6 [OK]
bitnami/nginx-ingress-controller Bitnami Docker Image for NGINX Ingress Contr… 5 [OK]
wodby/nginx Generic nginx 1 [OK]
ansibleplaybookbundle/nginx-apb An APB to deploy NGINX 1 [OK]
centos/nginx-110-centos7 Platform for running nginx 1.10 or building … 0
[root@hadoop001 ~]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
123275d6e508: Pull complete
6cd6a943ce27: Pull complete
a50b5ac4a7fb: Pull complete
Digest: sha256:d81f010955749350ef31a119fb94b180fde8b2f157da351ff5667ae037968b28
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
[root@hadoop001 ~]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
123275d6e508: Pull complete
6cd6a943ce27: Pull complete
a50b5ac4a7fb: Pull complete
Digest: sha256:d81f010955749350ef31a119fb94b180fde8b2f157da351ff5667ae037968b28
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest //:后面跟的是版本号,有时候版本号也存在文字格式的
#启动docker
[root@hadoop001 ~]# docker run --name ruozedata-nginx-g6-1 -d -p 881:80 nginx
[root@hadoop001 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d451f1c6272f nginx "nginx -g 'daemon of…" 10 seconds ago Up 9 seconds 0.0.0.0:881->80/tcp ruozedata-nginx-g6-1
[root@hadoop001 ~]#
Web UI展示
进入容器实例
[root@hadoop001 ~]# docker exec
"docker exec" requires at least 2 arguments.
See 'docker exec --help'.
Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
Run a command in a running container
[root@hadoop001 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d451f1c6272f nginx "nginx -g 'daemon of…" 10 seconds ago Up 9 seconds 0.0.0.0:881->80/tcp ruozedata-nginx-g6-1
[root@hadoop001 ~]# docker exec
"docker exec" requires at least 2 arguments.
See 'docker exec --help'.
Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
Run a command in a running container
[root@hadoop001 ~]# docker exec -it d451f1c6272f /bin/bash //这里跟的是容器ID
root@d451f1c6272f:/# //这时候就已经进入容器实例了,就相当于一个小的Linux操作系统
#clone一个session可以看到80端口号的进程,这就好解释一个容器其实就是一个进程
[root@hadoop001 ~]# ps -ef |grep docker
root 18841 1 0 12:37 ? 00:00:04 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
root 19361 18841 0 15:47 ? 00:00:00 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 881 -container-ip 172.17.0.2 -container-port 80
root 19376 18840 0 15:47 ? 00:00:00 containerd-shim -namespace moby -workdir /var/lib/containerd/io.containerd.runtime.v1.linux/moby/d451f1c6272f4f14ad7e56f96313fe8a6e4ad04f17cc7fad4b07a38d0366a0d7 -address /run/containerd/containerd.sock -containerd-binary /usr/bin/containerd -runtime-root /var/run/docker/runtime-runc
root 19479 19011 0 15:54 pts/0 00:00:00 docker exec -it d451f1c6272f /bin/bash
root 19523 19505 0 15:57 pts/1 00:00:00 grep --color=auto docker
[root@hadoop001 ~]#
容器也可以理解到分离,到了容器时代,就是分离的时代,就像计算和存储分离
root@d451f1c6272f:/# which ps
root@d451f1c6272f:/# which ls
/bin/ls
root@d451f1c6272f:/# ls /
bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var
可以发现进入容器这个微小的操作系统内,,进去后就可以做调试,不过有很多Linux有的命令这里是没有,因为这是简约版,不像完整版Linux操作系统有4个过G
正常的一般我们都是要做端口,外面封装一层Nginx
案例二
[root@hadoop001 ~]# mkdir -p docker/nginx/html
[root@hadoop001 ~]# cd docker/nginx/html/
[root@hadoop001 html]# yum -y install lrzsz
[root@hadoop001 html]# ll
total 4
-rw-r--r-- 1 root root 122 Apr 19 20:01 ruozedata.html
[root@hadoop001 html]# cat index.html
<html>
<body>
<p id="p1">Hello ruozedata</p>
<a href="http://www.ruozedata.com">www.ruozedata.com</a>
</body>
</html>
[root@hadoop001 html]#
[root@hadoop001 html]# curl http://47.100.61.26:881/ //在Linux机器上测试能否访问
<!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@hadoop001 html]# ll
total 4
-rw-r--r-- 1 root root 122 Apr 19 20:01 ruozedata.html
[root@hadoop001 html]# mv ruozedata.html index.html //nginx默认是index,除非强行指定
[root@hadoop001 html]# ll
total 4
-rw-r--r-- 1 root root 122 Apr 19 20:01 index.html
[root@hadoop001 html]# cd ../
[root@hadoop001 nginx]# ll
total 4
drwxr-xr-x 2 root root 4096 Apr 19 20:07 html
[root@hadoop001 nginx]# echo $PWD
/root/docker/nginx
[root@hadoop001 nginx]# docker run --name ruozedata-nginx-g6-2 -d -p 882:80 nginx -v $PWD/html:/usr/share/nginx/html:ro nginx:latest //-p是882端口映射到80,-v是当前路径有映射到指定路径,也就是取代他,-v 把本地的文件或文件夹 挂载到容器中,最后的参数ro 或rw控制这个挂载是否可读写
075df817dec71c8775e9031677c2f3b147ed0c2aba8439b999877cc84fdf32d2
[root@hadoop001 nginx]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
075df817dec7 nginx:latest "nginx -g 'daemon of…" 7 seconds ago Up 6 seconds 0.0.0.0:882->80/tcp ruozedata-nginx-g6-2
d451f1c6272f nginx "nginx -g 'daemon of…" 5 hours ago Up 5 hours 0.0.0.0:881->80/tcp ruozedata-nginx-g6-1
[root@hadoop001 nginx]# curl http://47.100.61.26:882/
<html>
<body>
<p id="p1">Hello ruozedata</p>
<a href="http://www.ruozedata.com">www.ruozedata.com</a>
</body>
</html>
[root@hadoop001 nginx]#
[root@hadoop001 nginx]# ps -ef |grep docker
root 18841 1 0 12:37 ? 00:00:05 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
root 19361 18841 0 15:47 ? 00:00:00 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 881 -container-ip 172.17.0.2 -container-port 80
root 19376 18840 0 15:47 ? 00:00:00 containerd-shim -namespace moby -workdir /var/lib/containerd/io.containerd.runtime.v1.linux/moby/d451f1c6272f4f14ad7e56f96313fe8a6e4ad04f17cc7fad4b07a38d0366a0d7 -address /run/containerd/containerd.sock -containerd-binary /usr/bin/containerd -runtime-root /var/run/docker/runtime-runc
root 20289 18841 0 20:39 ? 00:00:00 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 882 -container-ip 172.17.0.3 -container-port 80
root 20318 18840 0 20:39 ? 00:00:00 containerd-shim -namespace moby -workdir /var/lib/containerd/io.containerd.runtime.v1.linux/moby/075df817dec71c8775e9031677c2f3b147ed0c2aba8439b999877cc84fdf32d2 -address /run/containerd/containerd.sock -containerd-binary /usr/bin/containerd -runtime-root /var/run/docker/runtime-runc
root 20432 19011 0 20:58 pts/0 00:00:00 grep --color=auto docker
[root@hadoop001 nginx]#
案例三
[root@hadoop001 nginx]# docker search hello-world
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
hello-world Hello World! (an example of minimal Dockeriz… 1166 [OK]
kitematic/hello-world-nginx A light-weight nginx container that demonstr… 141
tutum/hello-world Image to test docker deployments. Has Apache… 70 [OK]
dockercloud/hello-world Hello World! 19 [OK]
crccheck/hello-world Hello World web server in under 2.5 MB 12 [OK]
vad1mo/hello-world-rest A simple REST Service that echoes back all t… 4 [OK]
ppc64le/hello-world Hello World! (an example of minimal Dockeriz… 2
ansibleplaybookbundle/hello-world-db-apb An APB which deploys a sample Hello World! a… 1 [OK]
carinamarina/hello-world-app This is a sample Python web application, run… 1 [OK]
markmnei/hello-world-java-docker Hello-World-Java-docker 1 [OK]
souravpatnaik/hello-world-go hello-world in Golang 1
datawire/hello-world Hello World! Simple Hello World implementati… 1 [OK]
ansibleplaybookbundle/hello-world-apb An APB which deploys a sample Hello World! a… 1 [OK]
rancher/hello-world 1
strimzi/hello-world-producer 0
burdz/hello-world-k8s To provide a simple webserver that can have … 0 [OK]
businessgeeks00/hello-world-nodejs 0
strimzi/hello-world-streams 0
koudaiii/hello-world 0
kevindockercompany/hello-world 0
freddiedevops/hello-world-spring-boot 0
infrastructureascode/hello-world A tiny "Hello World" web server with a healt… 0 [OK]
nirmata/hello-world 0 [OK]
uniplaces/hello-world 0
strimzi/hello-world-consumer 0
[root@hadoop001 nginx]#
[root@hadoop001 nginx]# docker pull hello-world
Using default tag: latest
latest: Pulling from library/hello-world
0e03bdcc26d7: Pull complete
Digest: sha256:8e3114318a995a1ee497790535e7b88365222a21771ae7e53687ad76563e8e76
Status: Downloaded newer image for hello-world:latest
docker.io/library/hello-world:latest
[root@hadoop001 nginx]#
[root@hadoop001 nginx]# docker run hello-world
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
[root@hadoop001 nginx]#
生产上nginx、http、tomcat、mysql等都是用docker来做的
案例四
docker 的mysql是用来给开发人员测试,但是正式生产库绝对不会用容器来做,原因很简单,docker底层还是以进程的形式运行,他需要通过网络,比如Windows环境下我们部署了VM虚拟机,这时候直接部署MySQL的话,那OK,但是假如你在VM虚拟机上面装了一个docker,然后又在docker上面装了MySQL,这时候多加了一层网络转发,那么这个网络转发的性能消耗大概在20%左右,记住一点未来上生产的涉及到存储的,比如说MySQL、Oracle等,这些绝对不能用docker来玩
[root@hadoop001 ~]# docker pull mysql:5.7
5.7: Pulling from library/mysql
123275d6e508: Already exists
27cddf5c7140: Pull complete
c17d442e14c9: Pull complete
2eb72ffed068: Pull complete
d4aa125eb616: Pull complete
52560afb169c: Pull complete
68190f37a1d2: Pull complete
3fd1dc6e2990: Pull complete
85a79b83df29: Pull complete
963449796e8c: Pull complete
003c42612f11: Pull complete
Digest: sha256:517d651577278f3e30ba93ad7c0ed342fdc8550bcde96a54b33ef0580ffec079
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7
[root@hadoop001 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mysql 5.7 273c7fcf9499 46 hours ago 455MB
nginx latest e791337790a6 2 days ago 127MB
hello-world latest bf756fb1ae65 3 months ago 13.3kB
[root@hadoop001 ~]#
[root@hadoop001 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
075df817dec7 nginx:latest "nginx -g 'daemon of…" 2 hours ago Up 2 hours 0.0.0.0:882->80/tcp ruozedata-nginx-g6-10
d451f1c6272f nginx "nginx -g 'daemon of…" 7 hours ago Up 7 hours 0.0.0.0:881->80/tcp ruozedata-nginx-g6-1
[root@hadoop001 ~]#
//ps只显示运行状态的,而helloworld是起来后就自动关了
[root@hadoop001 ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6988c2ae3b7f hello-world "/hello" 2 hours ago Exited (0) 2 hours ago goofy_montalcini
075df817dec7 nginx:latest "nginx -g 'daemon of…" 2 hours ago Up 2 hours 0.0.0.0:882->80/tcp ruozedata-nginx-g6-10
126ca0daebb8 nginx "-v /root/docker/ngi…" 3 hours ago Created 0.0.0.0:882->80/tcp ruozedata-nginx-g6-2
d451f1c6272f nginx "nginx -g 'daemon of…" 7 hours ago Up 7 hours 0.0.0.0:881->80/tcp ruozedata-nginx-g6-1
[root@hadoop001 ~]#
[root@hadoop001 ~]# docker run --name ruozedata-mysql-g6-1 -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.7
//这里需要指定版本号,不然会指定最新的
16cf525041bbb1a4c1b04ec108fe96b75f2286d7a0c36f1a6db076f8e8ea3e97
[root@hadoop001 ~]#
[root@hadoop001 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
16cf525041bb mysql:5.7 "docker-entrypoint.s…" 33 seconds ago Up 32 seconds 3306/tcp, 33060/tcp ruozedata-mysql-g6-1
075df817dec7 nginx:latest "nginx -g 'daemon of…" 2 hours ago Up 2 hours 0.0.0.0:882->80/tcp ruozedata-nginx-g6-10
d451f1c6272f nginx "nginx -g 'daemon of…" 7 hours ago Up 7 hours 0.0.0.0:881->80/tcp ruozedata-nginx-g6-1
[root@hadoop001 ~]#
[root@hadoop001 ~]# netstat -nlp |grep 3306
[root@hadoop001 ~]#
//发现没有3306端口号在运行
[root@hadoop001 ~]# docker restart 16cf525041bb
16cf525041bb
[root@hadoop001 ~]#
[root@hadoop001 ~]# docker exec -it 16cf525041bb /bin/bash
root@16cf525041bb:/#
root@16cf525041bb:/# mysql -uroot -p123456 -P3306
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.29 MySQL Community Server (GPL)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
//但是我们3306端口号没有对外映射,这时候就需要做以下操作
[root@hadoop001 ~]# docker run --name ruozedata-mysql-g6-2 -e MYSQL_ROOT_PASSWORD=123456 -p3306:3306 -d mysql:5.7
31a400ed60fec578098c3cc7605ac53fc3944a24cb413bcd19cf22fa7fe16c5a
[root@hadoop001 ~]#
[root@hadoop001 ~]# netstat -nlp |grep 3306
tcp6 0 0 :::3306 :::* LISTEN 21728/docker-proxy
[root@hadoop001 ~]#
//这时候海狸就可以连接了,但是肯定不能给root用户的密码
[root@hadoop001 ~]# docker exec -it eba30889a03b /bin/bash
root@eba30889a03b:/# mysql -uroot -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.29 MySQL Community Server (GPL)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create database ruozedata
-> ;
Query OK, 1 row affected (0.00 sec)
mysql> grant all privileges on *.* to rz@'%' identified by '123456'
-> ;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql>
最大的消耗都在网络转发
如何制作image
如何制作Dockerfile文件构建docker image? //Dockerfile专业名称,不然后面不认
就跳转到了github上面
https://github.com/docker-library/mysql/blob/26380f33a0fcd07dda35e37516eb24eaf962845c/5.7/
CentOS: yum
ubuntu: apt-get就可以当成yum用
[root@hadoop001 ~]# mkdir -p mysql/5.7
[root@hadoop001 ~]# cd mysql/5.7
[root@hadoop001 5.7]# cat Dockerfile //安装服务
FROM debian:buster-slim
# add our user and group first to make sure their IDs get assigned consistently, regardless of whatever dependencies get added
RUN groupadd -r mysql && useradd -r -g mysql mysql
RUN apt-get update && apt-get install -y --no-install-recommends gnupg dirmngr && rm -rf /var/lib/apt/lists/*
# add gosu for easy step-down from root
# https://github.com/tianon/gosu/releases
ENV GOSU_VERSION 1.12
RUN set -eux; \
savedAptMark="$(apt-mark showmanual)"; \
apt-get update; \
apt-get install -y --no-install-recommends ca-certificates wget; \
rm -rf /var/lib/apt/lists/*; \
dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')"; \
wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch"; \
wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch.asc"; \
export GNUPGHOME="$(mktemp -d)"; \
gpg --batch --keyserver hkps://keys.openpgp.org --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4; \
gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu; \
gpgconf --kill all; \
rm -rf "$GNUPGHOME" /usr/local/bin/gosu.asc; \
apt-mark auto '.*' > /dev/null; \
[ -z "$savedAptMark" ] || apt-mark manual $savedAptMark > /dev/null; \
apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \
chmod +x /usr/local/bin/gosu; \
gosu --version; \
gosu nobody true
RUN mkdir /docker-entrypoint-initdb.d
RUN apt-get update && apt-get install -y --no-install-recommends \
# for MYSQL_RANDOM_ROOT_PASSWORD
pwgen \
# for mysql_ssl_rsa_setup
openssl \
# FATAL ERROR: please install the following Perl modules before executing /usr/local/mysql/scripts/mysql_install_db:
# File::Basename
# File::Copy
# Sys::Hostname
# Data::Dumper
perl \
# install "xz-utils" for .sql.xz docker-entrypoint-initdb.d files
xz-utils \
&& rm -rf /var/lib/apt/lists/*
RUN set -ex; \
# gpg: key 5072E1F5: public key "MySQL Release Engineering <[email protected]>" imported
key='A4A9406876FCBD3C456770C88C718D3B5072E1F5'; \
export GNUPGHOME="$(mktemp -d)"; \
gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key"; \
gpg --batch --export "$key" > /etc/apt/trusted.gpg.d/mysql.gpg; \
gpgconf --kill all; \
rm -rf "$GNUPGHOME"; \
apt-key list > /dev/null
ENV MYSQL_MAJOR 5.7
ENV MYSQL_VERSION 5.7.29-1debian10
RUN echo "deb http://repo.mysql.com/apt/debian/ buster mysql-${MYSQL_MAJOR}" > /etc/apt/sources.list.d/mysql.list
# the "/var/lib/mysql" stuff here is because the mysql-server postinst doesn't have an explicit way to disable the mysql_install_db codepath besides having a database already "configured" (ie, stuff in /var/lib/mysql/mysql)
# also, we set debconf keys to make APT a little quieter
RUN { \
echo mysql-community-server mysql-community-server/data-dir select ''; \
echo mysql-community-server mysql-community-server/root-pass password ''; \
echo mysql-community-server mysql-community-server/re-root-pass password ''; \
echo mysql-community-server mysql-community-server/remove-test-db select false; \
} | debconf-set-selections \
&& apt-get update && apt-get install -y mysql-server="${MYSQL_VERSION}" && rm -rf /var/lib/apt/lists/* \
&& rm -rf /var/lib/mysql && mkdir -p /var/lib/mysql /var/run/mysqld \
&& chown -R mysql:mysql /var/lib/mysql /var/run/mysqld \
# ensure that /var/run/mysqld (used for socket and lock files) is writable regardless of the UID our mysqld instance ends up having at runtime
&& chmod 777 /var/run/mysqld \
# comment out a few problematic configuration values
&& find /etc/mysql/ -name '*.cnf' -print0 \
| xargs -0 grep -lZE '^(bind-address|log)' \
| xargs -rt -0 sed -Ei 's/^(bind-address|log)/#&/' \
# don't reverse lookup hostnames, they are usually another container
&& echo '[mysqld]\nskip-host-cache\nskip-name-resolve' > /etc/mysql/conf.d/docker.cnf
VOLUME /var/lib/mysql
COPY docker-entrypoint.sh /usr/local/bin/
RUN ln -s usr/local/bin/docker-entrypoint.sh /entrypoint.sh # backwards compat
ENTRYPOINT ["docker-entrypoint.sh"]
EXPOSE 3306 33060
CMD ["mysqld"]
[root@hadoop001 5.7]# cat docker-entrypoint.sh
#!/bin/bash
set -eo pipefail
shopt -s nullglob
# logging functions
mysql_log() {
local type="$1"; shift
printf '%s [%s] [Entrypoint]: %s\n' "$(date --rfc-3339=seconds)" "$type" "$*"
}
mysql_note() {
mysql_log Note "$@"
}
mysql_warn() {
mysql_log Warn "$@" >&2
}
mysql_error() {
mysql_log ERROR "$@" >&2
exit 1
}
# usage: file_env VAR [DEFAULT]
# ie: file_env 'XYZ_DB_PASSWORD' 'example'
# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
# "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
file_env() {
local var="$1"
local fileVar="${var}_FILE"
local def="${2:-}"
if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
mysql_error "Both $var and $fileVar are set (but are exclusive)"
fi
local val="$def"
if [ "${!var:-}" ]; then
val="${!var}"
elif [ "${!fileVar:-}" ]; then
val="$(< "${!fileVar}")"
fi
export "$var"="$val"
unset "$fileVar"
}
# check to see if this file is being run or sourced from another script
_is_sourced() {
# https://unix.stackexchange.com/a/215279
[ "${#FUNCNAME[@]}" -ge 2 ] \
&& [ "${FUNCNAME[0]}" = '_is_sourced' ] \
&& [ "${FUNCNAME[1]}" = 'source' ]
}
# usage: docker_process_init_files [file [file [...]]]
# ie: docker_process_init_files /always-initdb.d/*
# process initializer files, based on file extensions
docker_process_init_files() {
# mysql here for backwards compatibility "${mysql[@]}"
mysql=( docker_process_sql )
echo
local f
for f; do
case "$f" in
*.sh) mysql_note "$0: running $f"; . "$f" ;;
*.sql) mysql_note "$0: running $f"; docker_process_sql < "$f"; echo ;;
*.sql.gz) mysql_note "$0: running $f"; gunzip -c "$f" | docker_process_sql; echo ;;
*.sql.xz) mysql_note "$0: running $f"; xzcat "$f" | docker_process_sql; echo ;;
*) mysql_warn "$0: ignoring $f" ;;
esac
echo
done
}
mysql_check_config() {
local toRun=( "$@" --verbose --help ) errors
if ! errors="$("${toRun[@]}" 2>&1 >/dev/null)"; then
mysql_error $'mysqld failed while attempting to check config\n\tcommand was: '"${toRun[*]}"$'\n\t'"$errors"
fi
}
# Fetch value from server config
# We use mysqld --verbose --help instead of my_print_defaults because the
# latter only show values present in config files, and not server defaults
mysql_get_config() {
local conf="$1"; shift
"$@" --verbose --help --log-bin-index="$(mktemp -u)" 2>/dev/null \
| awk -v conf="$conf" '$1 == conf && /^[^ \t]/ { sub(/^[^ \t]+[ \t]+/, ""); print; exit }'
# match "datadir /some/path with/spaces in/it here" but not "--xyz=abc\n datadir (xyz)"
}
# Do a temporary startup of the MySQL server, for init purposes
docker_temp_server_start() {
if [ "${MYSQL_MAJOR}" = '5.6' ] || [ "${MYSQL_MAJOR}" = '5.7' ]; then
"$@" --skip-networking --socket="${SOCKET}" &
mysql_note "Waiting for server startup"
local i
for i in {30..0}; do
# only use the root password if the database has already been initializaed
# so that it won't try to fill in a password file when it hasn't been set yet
extraArgs=()
if [ -z "$DATABASE_ALREADY_EXISTS" ]; then
extraArgs+=( '--dont-use-mysql-root-password' )
fi
if docker_process_sql "${extraArgs[@]}" --database=mysql <<<'SELECT 1' &> /dev/null; then
break
fi
sleep 1
done
if [ "$i" = 0 ]; then
mysql_error "Unable to start server."
fi
else
# For 5.7+ the server is ready for use as soon as startup command unblocks
if ! "$@" --daemonize --skip-networking --socket="${SOCKET}"; then
mysql_error "Unable to start server."
fi
fi
}
# Stop the server. When using a local socket file mysqladmin will block until
# the shutdown is complete.
docker_temp_server_stop() {
if ! mysqladmin --defaults-extra-file=<( _mysql_passfile ) shutdown -uroot --socket="${SOCKET}"; then
mysql_error "Unable to shut down server."
fi
}
# Verify that the minimally required password settings are set for new databases.
docker_verify_minimum_env() {
if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
mysql_error $'Database is uninitialized and password option is not specified\n\tYou need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD'
fi
}
# creates folders for the database
# also ensures permission for user mysql of run as root
docker_create_db_directories() {
local user; user="$(id -u)"
# TODO other directories that are used by default? like /var/lib/mysql-files
# see https://github.com/docker-library/mysql/issues/562
mkdir -p "$DATADIR"
if [ "$user" = "0" ]; then
# this will cause less disk access than `chown -R`
find "$DATADIR" \! -user mysql -exec chown mysql '{}' +
fi
}
# initializes the database directory
docker_init_database_dir() {
mysql_note "Initializing database files"
if [ "$MYSQL_MAJOR" = '5.6' ]; then
mysql_install_db --datadir="$DATADIR" --rpm --keep-my-cnf "${@:2}"
else
"$@" --initialize-insecure
fi
mysql_note "Database files initialized"
if command -v mysql_ssl_rsa_setup > /dev/null && [ ! -e "$DATADIR/server-key.pem" ]; then
# https://github.com/mysql/mysql-server/blob/23032807537d8dd8ee4ec1c4d40f0633cd4e12f9/packaging/deb-in/extra/mysql-systemd-start#L81-L84
mysql_note "Initializing certificates"
mysql_ssl_rsa_setup --datadir="$DATADIR"
mysql_note "Certificates initialized"
fi
}
# Loads various settings that are used elsewhere in the script
# This should be called after mysql_check_config, but before any other functions
docker_setup_env() {
# Get config
declare -g DATADIR SOCKET
DATADIR="$(mysql_get_config 'datadir' "$@")"
SOCKET="$(mysql_get_config 'socket' "$@")"
# Initialize values that might be stored in a file
file_env 'MYSQL_ROOT_HOST' '%'
file_env 'MYSQL_DATABASE'
file_env 'MYSQL_USER'
file_env 'MYSQL_PASSWORD'
file_env 'MYSQL_ROOT_PASSWORD'
declare -g DATABASE_ALREADY_EXISTS
if [ -d "$DATADIR/mysql" ]; then
DATABASE_ALREADY_EXISTS='true'
fi
}
# Execute sql script, passed via stdin
# usage: docker_process_sql [--dont-use-mysql-root-password] [mysql-cli-args]
# ie: docker_process_sql --database=mydb <<<'INSERT ...'
# ie: docker_process_sql --dont-use-mysql-root-password --database=mydb <my-file.sql
docker_process_sql() {
passfileArgs=()
if [ '--dont-use-mysql-root-password' = "$1" ]; then
passfileArgs+=( "$1" )
shift
fi
# args sent in can override this db, since they will be later in the command
if [ -n "$MYSQL_DATABASE" ]; then
set -- --database="$MYSQL_DATABASE" "$@"
fi
mysql --defaults-extra-file=<( _mysql_passfile "${passfileArgs[@]}") --protocol=socket -uroot -hlocalhost --socket="${SOCKET}" "$@"
}
# Initializes database with timezone info and root password, plus optional extra db/user
docker_setup_db() {
# Load timezone info into database
if [ -z "$MYSQL_INITDB_SKIP_TZINFO" ]; then
# sed is for https://bugs.mysql.com/bug.php?id=20545
mysql_tzinfo_to_sql /usr/share/zoneinfo \
| sed 's/Local time zone must be set--see zic manual page/FCTY/' \
| docker_process_sql --dont-use-mysql-root-password --database=mysql
# tell docker_process_sql to not use MYSQL_ROOT_PASSWORD since it is not set yet
fi
# Generate random root password
if [ -n "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
export MYSQL_ROOT_PASSWORD="$(pwgen -1 32)"
mysql_note "GENERATED ROOT PASSWORD: $MYSQL_ROOT_PASSWORD"
fi
# Sets root password and creates root users for non-localhost hosts
local rootCreate=
# default root to listen for connections from anywhere
if [ -n "$MYSQL_ROOT_HOST" ] && [ "$MYSQL_ROOT_HOST" != 'localhost' ]; then
# no, we don't care if read finds a terminating character in this heredoc
# https://unix.stackexchange.com/questions/265149/why-is-set-o-errexit-breaking-this-read-heredoc-expression/265151#265151
read -r -d '' rootCreate <<-EOSQL || true
CREATE USER 'root'@'${MYSQL_ROOT_HOST}' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}' ;
GRANT ALL ON *.* TO 'root'@'${MYSQL_ROOT_HOST}' WITH GRANT OPTION ;
EOSQL
fi
local passwordSet=
if [ "$MYSQL_MAJOR" = '5.6' ]; then
# no, we don't care if read finds a terminating character in this heredoc (see above)
read -r -d '' passwordSet <<-EOSQL || true
DELETE FROM mysql.user WHERE user NOT IN ('mysql.sys', 'mysqlxsys', 'root') OR host NOT IN ('localhost') ;
SET PASSWORD FOR 'root'@'localhost'=PASSWORD('${MYSQL_ROOT_PASSWORD}') ;
-- 5.5: https://github.com/mysql/mysql-server/blob/e48d775c6f066add457fa8cfb2ebc4d5ff0c7613/scripts/mysql_secure_installation.sh#L192-L210
-- 5.6: https://github.com/mysql/mysql-server/blob/06bc670db0c0e45b3ea11409382a5c315961f682/scripts/mysql_secure_installation.sh#L218-L236
-- 5.7: https://github.com/mysql/mysql-server/blob/913071c0b16cc03e703308250d795bc381627e37/client/mysql_secure_installation.cc#L792-L818
-- 8.0: https://github.com/mysql/mysql-server/blob/b93c1661d689c8b7decc7563ba15f6ed140a4eb6/client/mysql_secure_installation.cc#L726-L749
DELETE FROM mysql.db WHERE Db='test' OR Db='test\_%' ;
-- https://github.com/docker-library/mysql/pull/479#issuecomment-414561272 ("This is only needed for 5.5 and 5.6")
EOSQL
else
# no, we don't care if read finds a terminating character in this heredoc (see above)
read -r -d '' passwordSet <<-EOSQL || true
ALTER USER 'root'@'localhost' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}' ;
EOSQL
fi
# tell docker_process_sql to not use MYSQL_ROOT_PASSWORD since it is just now being set
docker_process_sql --dont-use-mysql-root-password --database=mysql <<-EOSQL
-- What's done in this file shouldn't be replicated
-- or products like mysql-fabric won't work
SET @@SESSION.SQL_LOG_BIN=0;
${passwordSet}
GRANT ALL ON *.* TO 'root'@'localhost' WITH GRANT OPTION ;
FLUSH PRIVILEGES ;
${rootCreate}
DROP DATABASE IF EXISTS test ;
EOSQL
# Creates a custom database and user if specified
if [ -n "$MYSQL_DATABASE" ]; then
mysql_note "Creating database ${MYSQL_DATABASE}"
docker_process_sql --database=mysql <<<"CREATE DATABASE IF NOT EXISTS \`$MYSQL_DATABASE\` ;"
fi
if [ -n "$MYSQL_USER" ] && [ -n "$MYSQL_PASSWORD" ]; then
mysql_note "Creating user ${MYSQL_USER}"
docker_process_sql --database=mysql <<<"CREATE USER '$MYSQL_USER'@'%' IDENTIFIED BY '$MYSQL_PASSWORD' ;"
if [ -n "$MYSQL_DATABASE" ]; then
mysql_note "Giving user ${MYSQL_USER} access to schema ${MYSQL_DATABASE}"
docker_process_sql --database=mysql <<<"GRANT ALL ON \`$MYSQL_DATABASE\`.* TO '$MYSQL_USER'@'%' ;"
fi
docker_process_sql --database=mysql <<<"FLUSH PRIVILEGES ;"
fi
}
_mysql_passfile() {
# echo the password to the "file" the client uses
# the client command will use process substitution to create a file on the fly
# ie: --defaults-extra-file=<( _mysql_passfile )
if [ '--dont-use-mysql-root-password' != "$1" ] && [ -n "$MYSQL_ROOT_PASSWORD" ]; then
cat <<-EOF
[client]
password="${MYSQL_ROOT_PASSWORD}"
EOF
fi
}
# Mark root user as expired so the password must be changed before anything
# else can be done (only supported for 5.6+)
mysql_expire_root_user() {
if [ -n "$MYSQL_ONETIME_PASSWORD" ]; then
docker_process_sql --database=mysql <<-EOSQL
ALTER USER 'root'@'%' PASSWORD EXPIRE;
EOSQL
fi
}
# check arguments for an option that would cause mysqld to stop
# return true if there is one
_mysql_want_help() {
local arg
for arg; do
case "$arg" in
-'?'|--help|--print-defaults|-V|--version)
return 0
;;
esac
done
return 1
}
_main() {
# if command starts with an option, prepend mysqld
if [ "${1:0:1}" = '-' ]; then
set -- mysqld "$@"
fi
# skip setup if they aren't running mysqld or want an option that stops mysqld
if [ "$1" = 'mysqld' ] && ! _mysql_want_help "$@"; then
mysql_note "Entrypoint script for MySQL Server ${MYSQL_VERSION} started."
mysql_check_config "$@"
# Load various environment variables
docker_setup_env "$@"
docker_create_db_directories
# If container is started as root user, restart as dedicated mysql user
if [ "$(id -u)" = "0" ]; then
mysql_note "Switching to dedicated user 'mysql'"
exec gosu mysql "$BASH_SOURCE" "$@"
fi
# there's no database, so it needs to be initialized
if [ -z "$DATABASE_ALREADY_EXISTS" ]; then
docker_verify_minimum_env
# check dir permissions to reduce likelihood of half-initialized database
ls /docker-entrypoint-initdb.d/ > /dev/null
docker_init_database_dir "$@"
mysql_note "Starting temporary server"
docker_temp_server_start "$@"
mysql_note "Temporary server started."
docker_setup_db
docker_process_init_files /docker-entrypoint-initdb.d/*
mysql_expire_root_user
mysql_note "Stopping temporary server"
docker_temp_server_stop
mysql_note "Temporary server stopped"
echo
mysql_note "MySQL init process done. Ready for start up."
echo
fi
fi
exec "$@"
}
# If we are sourced from elsewhere, don't perform any further actions
if ! _is_sourced; then
_main "$@"
fi
[root@hadoop001 5.7]# ll
total 24
-rw-r--r-- 1 root root 12934 Apr 20 12:41 docker-entrypoint.sh
-rw-r--r-- 1 root root 4128 Apr 20 12:39 Dockerfile
[root@hadoop001 5.7]#
[root@hadoop001 5.7]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
eba30889a03b mysql:5.7 "docker-entrypoint.s…" 13 minutes ago Up 13 minutes 0.0.0.0:3306->3306/tcp, 33060/tcp ruozedata-mysql-g6-3
[root@hadoop001 5.7]# docker stop eba30889a03b
eba30889a03b
[root@hadoop001 5.7]#
[root@hadoop001 5.7]# docker build . -t mysql:rz //制作镜像,-t指定名字
就像上面安装完需要创建用户并赋权限,这些都可以自定义到镜像中,构建镜像就可以减少重复劳动力
[root@hadoop001 lib]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mysql rz 2360233f9f6a 4 minutes ago 454MB
mysql 5.7 273c7fcf9499 2 days ago 455MB
nginx latest e791337790a6 2 days ago 127MB
debian buster-slim 4e22ed854b0a 4 days ago 69.2MB
hello-world latest bf756fb1ae65 3 months ago 13.3kB
[root@hadoop001 lib]#
Dockerfile里面主要信息
- FROM 基础镜像
- MAINTAINER 维护者信息
- RUN 镜像的Linux操作命令 //正常只有一个,不能起多个
- ENTRYPOINT 配置容器启动后只需的命令
- 每个Dockerfile文件只能有一个ENTRYPOINT,当然可以指定多个,只有最后一个生效;对外叫docker,真正用的时候叫container,ENTRYPOINT就是container容器
- EXPOSE 运行的哪个端口号
- CMD 启动进程服务
当然并不是所有的都能跑在docker上,CDH不能用docker来跑,因为CDH太重了,docker是轻量级的、便捷的、可以运行在任何地方,而CDH底层依赖Java、python
之前要存储和计算在一块,这叫数据本地化;当然现在由于网络带宽等已经能够弥补这块性能的消耗,所以就产生了现在的计算和存储分离的趋势