docker实践

docker 实践

一、准备docker环境

参考https://www.cnblogs.com/walker-lin/p/11214127.html
(1)切换到root
(2)apt-get update
(3)允许apt通过https使用repository安装软件包

apt-get install \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg-agent \
    software-properties-common

(4)添加Docker官方GPG key

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
官方的在国外,太慢了,建议用国内阿里云版
(国内阿里云版 curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | apt-key add -

(5)验证key的指纹

apt-key fingerprint 0EBFCD88

输出为:

root@xumy-VirtualBox:/home/xumy# apt-key fingerprint 0EBFCD88
pub   rsa4096 2017-02-22 [SCEA]
      9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
uid           [ 未知 ] Docker Release (CE deb) <docker@docker.com>
sub   rsa4096 2017-02-22 [S]

(6)添加稳定版repository

add-apt-repository
“deb [arch=amd64] https://download.docker.com/linux/ubuntu
$(lsb_release -cs)
stable”

还是推荐国内阿里云版:

add-apt-repository \
   "deb [arch=amd64] https://mirrors.aliyun.com/docker-ce/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

(7)sudo apt-get update

(8)安装最新版本的docker ce和containerd

sudo apt-get install docker-ce docker-ce-cli containerd.io
安装完成。

检查docker安装
root@xumy-VirtualBox:/home/xumy# docker --version
Docker version 20.10.1, build 831ebea

二、运行第一个容器

运行镜像
root@xumy-VirtualBox:/home/xumy# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
0e03bdcc26d7: Pull complete 
Digest: sha256:1a523af650137b8accdaed439c17d684df61ee4d74feac151b5b337bd29e7eec
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/

安装ubuntu镜像

xumy@xumy-VirtualBox:~$ docker run -it ubuntu bash
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
da7391352a9b: Downloading  2.055MB/28.56MB
14428a6d4bcd: Download complete 
2c2d948710f2: Download complete 

一般情况下会超时,所以需要更换一下docker的源,源可以参考https://www.cnblogs.com/bobkingblog/p/11106236.html,挑选一个能用的即可。

修改daemon.json的内容如下:

{
  "registry-mirrors": ["https://9cpn8tt6.mirror.aliyuncs.com"]
}

然后重启docker服务,之后下载就很快啦。

xumy@xumy-VirtualBox:/etc/docker$ su
密码: 
root@xumy-VirtualBox:/etc/docker# vim daemon.json
root@xumy-VirtualBox:/etc/docker# systemctl daemon-reload
root@xumy-VirtualBox:/etc/docker# systemctl restart docker
root@xumy-VirtualBox:/etc/docker# docker --version
Docker version 20.10.1, build 831ebea
root@xumy-VirtualBox:/etc/docker# docker run -it ubuntu bash
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
da7391352a9b: Pull complete 
14428a6d4bcd: Pull complete 
2c2d948710f2: Pull complete 
Digest: sha256:c95a8e48bf88e9849f3e0f723d9f49fa12c5a00cfc6e60d2bc99d87555295e4c
Status: Downloaded newer image for ubuntu:latest
root@9ec8e1f47caf:/# exit
exit
root@xumy-VirtualBox:/etc/docker# 

三、docker基本操作

显示本地镜像库内容
root@xumy-VirtualBox:/etc/docker# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
ubuntu        latest    f643c72bc252   4 weeks ago     72.9MB
hello-world   latest    bf756fb1ae65   11 months ago   13.3kB

获得帮助
xumy@xumy-VirtualBox:/etc/docker# docker --help

Usage:	docker [OPTIONS] COMMAND

显示运行中容器

docker container ls 可以简写为 docker ps

root@xumy-VirtualBox:/etc/docker# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
显示所有容器,包含已终止的容器
root@xumy-VirtualBox:/etc/docker# docker ps -a
CONTAINER ID   IMAGE         COMMAND    CREATED          STATUS                            PORTS     NAMES
9ec8e1f47caf   ubuntu        "bash"     4 minutes ago    Exited (127) About a minute ago             focused_moser
e8c49a7a68c2   hello-world   "/hello"   14 minutes ago   Exited (0) 14 minutes ago                   friendly_chatterjee

继续运行原容器并进入
root@xumy-VirtualBox:/etc/docker# docker restart focused_moser
focused_moser
root@xumy-VirtualBox:/etc/docker# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED         STATUS         PORTS     NAMES
9ec8e1f47caf   ubuntu    "bash"    9 minutes ago   Up 3 seconds             focused_moser

相当于docker里又运行了一个ubuntu,主机名为9ec8e1f47caf

root@xumy-VirtualBox:/etc/docker# docker attach focused_moser
root@9ec8e1f47caf:/# ls
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

三、mysql与容器化

拉取mysql镜像
root@xumy-VirtualBox:/etc/docker# docker pull mysql:5.7
5.7: Pulling from library/mysql
6ec7b7d162b2: Pull complete 
fedd960d3481: Pull complete 
7ab947313861: Pull complete 
64f92f19e638: Pull complete 
3e80b17bff96: Pull complete 
014e976799f9: Pull complete 
59ae84fee1b3: Pull complete 
7d1da2a18e2e: Pull complete 
301a28b700b9: Pull complete 
529dc8dbeaf3: Pull complete 
bc9d021dc13f: Pull complete 
Digest: sha256:c3a567d3e3ad8b05dfce401ed08f0f6bf3f3b64cc17694979d5f2e5d78e10173
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

构建docker镜像练习
root@xumy-VirtualBox:/etc/docker# cd ~
root@xumy-VirtualBox:~# mkdir mydock
root@xumy-VirtualBox:~# cd mydock
root@xumy-VirtualBox:~/mydock# vim dockerfile

键入以下内容

FROM ubuntu
ENTRYPOINT ["top", "-b"]
CMD ["-c"]

构建镜像

root@xumy-VirtualBox:~/mydock# docker build . -t hello
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM ubuntu
 ---> f643c72bc252
Step 2/3 : ENTRYPOINT ["top", "-b"]
 ---> Running in 3a6fdc39e210
Removing intermediate container 3a6fdc39e210
 ---> 7dba343e91d7
Step 3/3 : CMD ["-c"]
 ---> Running in eba9014c2fa5
Removing intermediate container eba9014c2fa5
 ---> b138b27e81ef
Successfully built b138b27e81ef
Successfully tagged hello:latest

运行镜像

root@xumy-VirtualBox:~/mydock# docker run -it --rm hello -H
top - 05:20:23 up  2:23,  0 users,  load average: 0.59, 0.14, 0.04
Threads:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem :   2926.4 total,    187.1 free,   1392.2 used,   1347.1 buff/cache
MiB Swap:   1186.4 total,   1172.8 free,     13.6 used.   1209.3 avail Mem 

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
    1 root      20   0    5968   3148   2724 R   0.0   0.1   0:00.03 top


使用mysql容器

启动服务器

root@xumy-VirtualBox:~# docker run -p 3306:3306 --name mysql2 -e  MYSQL_ROOT_PASSWORD=root -d mysql:5.7
e204a3304ca62670eed7a0e133b9b420d017c4079b540a3771bca74aca031884
root@xumy-VirtualBox:~# docker ps
CONTAINER ID   IMAGE       COMMAND                  CREATED          STATUS         PORTS                               NAMES
e204a3304ca6   mysql:5.7   "docker-entrypoint.s…"   10 seconds ago   Up 9 seconds   0.0.0.0:3306->3306/tcp, 33060/tcp   mysql2

启动mysql客户端

root@xumy-VirtualBox:~# docker run -it --net host mysql:5.7 "sh"
# mysql -h127.0.0.1 -P3306 -uroot -proot
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 2
Server version: 5.7.32 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> 

查看数据库

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> 

四、docker网络

管理容器网络

root@xumy-VirtualBox:~# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
9951d2b784e8   bridge    bridge    local
48db1397be63   host      host      local
3970302d90fd   none      null      local

有bridge和host模式,分别为连接本机内网络和使用主机网卡。

制备支持ipconfig和ping命令的ubuntu容器

root@xumy-VirtualBox:~#  docker run --name unet -it --rm ubuntu bash
root@537441333c78:/# apt-get update
Get:1 http://security.ubuntu.com/ubuntu focal-security InRelease [109 kB]  
...                                                                                                                                                                 
root@537441333c78:/# apt-get install net-tools
...
root@537441333c78:/#  apt-get install iputils-ping -y
...
root@537441333c78:/# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.0.3  netmask 255.255.0.0  broadcast 172.17.255.255
        ether 02:42:ac:11:00:03  txqueuelen 0  (Ethernet)
        RX packets 10658  bytes 17630050 (17.6 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 6005  bytes 524464 (524.4 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

在ubuntu容器内ping容器外的我的主机ip

root@537441333c78:/# ping 172.26.113.186
PING 172.26.113.186 (172.26.113.186) 56(84) bytes of data.
64 bytes from 172.26.113.186: icmp_seq=1 ttl=64 time=0.057 ms
64 bytes from 172.26.113.186: icmp_seq=2 ttl=64 time=0.054 ms
64 bytes from 172.26.113.186: icmp_seq=3 ttl=64 time=0.077 ms
64 bytes from 172.26.113.186: icmp_seq=4 ttl=64 time=0.057 ms
64 bytes from 172.26.113.186: icmp_seq=5 ttl=64 time=0.053 ms
64 bytes from 172.26.113.186: icmp_seq=6 ttl=64 time=0.058 ms
64 bytes from 172.26.113.186: icmp_seq=7 ttl=64 time=0.091 ms
64 bytes from 172.26.113.186: icmp_seq=8 ttl=64 time=0.075 ms
64 bytes from 172.26.113.186: icmp_seq=9 ttl=64 time=0.079 ms
64 bytes from 172.26.113.186: icmp_seq=10 ttl=64 time=0.078 ms
64 bytes from 172.26.113.186: icmp_seq=11 ttl=64 time=0.071 ms
64 bytes from 172.26.113.186: icmp_seq=12 ttl=64 time=0.236 ms
^C
--- 172.26.113.186 ping statistics ---
12 packets transmitted, 12 received, 0% packet loss, time 11244ms
rtt min/avg/max/mdev = 0.053/0.082/0.236/0.047 ms

五、容器监控与日志

检查docker的状态

root@xumy-VirtualBox:~# docker info
Client:
 Context:    default
 Debug Mode: false
 Plugins:
  app: Docker App (Docker Inc., v0.9.1-beta3)
  buildx: Build with BuildKit (Docker Inc., v0.5.0-docker)

Server:
 Containers: 5
  Running: 1
  Paused: 0
  Stopped: 4
 Images: 5
 Server Version: 20.10.1
 Storage Driver: overlay2
...

查看容器内进程

  • 首先查看有哪些容器正在运行
root@xumy-VirtualBox:~# docker ps
CONTAINER ID   IMAGE       COMMAND                  CREATED          STATUS          PORTS                               NAMES
e204a3304ca6   mysql:5.7   "docker-entrypoint.s…"   28 minutes ago   Up 28 minutes   0.0.0.0:3306->3306/tcp, 33060/tcp   mysql2
  • 只有一个容器,查看该容器的进程
root@xumy-VirtualBox:~# docker top e204a3304ca6
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
vboxadd             9158                9133                0                   13:24               ?                   00:00:01            mysqld

查看容器日志
前面操作过ubuntu,现在将日志打印出来

root@xumy-VirtualBox:~# docker ps -a
CONTAINER ID   IMAGE         COMMAND                  CREATED             STATUS                         PORTS                               NAMES
c550e2391eca   mysql:5.7     "docker-entrypoint.s…"   28 minutes ago      Exited (0) 22 minutes ago                                          cool_elbakyan
08f6b0ec8019   mysql:5.7     "docker-entrypoint.s…"   29 minutes ago      Exited (130) 28 minutes ago                                        cool_franklin
e204a3304ca6   mysql:5.7     "docker-entrypoint.s…"   30 minutes ago      Up 30 minutes                  0.0.0.0:3306->3306/tcp, 33060/tcp   mysql2
9ec8e1f47caf   ubuntu        "bash"                   About an hour ago   Exited (0) About an hour ago                                       focused_moser
e8c49a7a68c2   hello-world   "/hello"                 2 hours ago         Exited (0) 2 hours ago                                             friendly_chatterjee
root@xumy-VirtualBox:~# docker logs 9ec8e1f47caf
root@9ec8e1f47caf:/# docker images
bash: docker: command not found
root@9ec8e1f47caf:/# exit
exit
root@9ec8e1f47caf:/# exit
root@9ec8e1f47caf:/# ls
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@9ec8e1f47caf:/# exit
exit

这些日志保存起来有利于后续地调试与分析。

六、golang应用容器化

参考https://zhuanlan.zhihu.com/p/143200936
首先创建一个超级简单的web服务器,只需实现一个文件main.go

//main.go
package main

import (
    "fmt"
    "net/http"
)
 
func main() {
    http.HandleFunc("/", home)
    http.ListenAndServe(":8080", nil)
}
 
func home(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "welcome to the main page of a single web!")
}

然后运行main.go,在浏览器访问本机的8080端口就会看到“welcome to the main page of a single web!”的响应信息。

接下来将这个web应用打包成docker中的镜像。
在当前包的路径下创建一个文件,文件名为dockerfile,文件内容如下

# 选择基础镜像
FROM golang:1.14.3-alpine

# 修改使用国内代理, 否则会很慢
RUN set -ex \
&& go env -w GO111MODULE=on \
&& go env -w GOPROXY=https://goproxy.cn,direct

# 在镜像中创建项目目录
RUN mkdir /app

# 将宿主项目目录(也是当前目录)下所有文件
# 复制到镜像中的项目目录
ADD . /app

# 工作路径
WORKDIR /app

# 创建项目的可执行文件web-server
RUN go build -o single-web-server *.go

# 执行web-server
CMD ["/app/single-web-server"]

然后终端进入root模式,运行docker build -t single-web-server .,注意不要漏掉最后的点。

然后通过docker images命令查看刚刚创建好的镜像

最后创建新的容器并运行该web服务器
(镜像相当于可执行程序,容器相当于进程)
# docker run -p 8080:9999 -it single-web-server

-p 8080:8080 - 宿主端口8080映射到容器端口8080
-it 输出打印到控制台上
-single-web-server - 镜像名称

七、小结

写这篇博客的过程是从对docker一无所知到有一个大致的整体印象。docker是容器,容器内可以包含许多应用,只要你需要就可以通过docker将应用拉取下来,逐渐形成属于你的应用集。
对于开发者,docker让他们可以打包他们的应用以及应用运行的上下文环境到一个可移植的镜像中,然后发布到任何支持Docker的系统上运行。 通过容器技术,在几乎没有性能开销的情况下,Docker 为应用提供了一个隔离运行环境。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值