DOCKER学习_008:Docker容器的运行最佳实践

01/01 16:34
阅读数 33

一 容器分类

容器按用途大致可分为两类:

服务类容器,如 web server、 database等

工具类容器,如cur容器, Iredis-cli容器

通常而言,服务类容器需要长期运行,所以使用 daemon的方式运行;而工作类环境通常是给我们提供一个临时的工作环境,所以一般以runt的方式在前台运行

容器的短任务和长任务

长任务就是长期执行的任务,比如容器监听在某个端口上,只要放在后台运行即可(http,nginx,myslq等)

二 工具类容器

2.1 简单实验

如执行一个docker run centos:7 /bin/bash,就是一个短任务,结束终端退出,容器就关闭了

[root@docker-server3 ~]# docker run -it centos:7 /bin/bash

Unable to find image 'centos:7' locally
7: Pulling from library/centos
ab5ef0e58194: Pull complete 
Digest: sha256:4a701376d03f6b39b8c2a8f4a8e499441b0d567f9ab9d58e4991de4472fb813c
Status: Downloaded newer image for centos:7
[root@5e82ea0e65f0 /]#

[root@5e82ea0e65f0 /]# exit
exit
[root@docker-server3 ~]# docker ps -a

CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS                     PORTS               NAMES
5e82ea0e65f0        centos:7            "/bin/bash"         About a minute ago   Exited (0) 6 seconds ago                       romantic_lewin

执行完成就退出

在退出后,容器不会删除,start后依然可以做操作

[root@docker-server3 ~]# docker start 5e82ea0e65f0

[root@docker-server3 ~]# docker ps -a

CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS               NAMES
5e82ea0e65f0        centos:7            "/bin/bash"         About a minute ago   Up 1 second                             romantic_lewin

再次进入容器进行操作

[root@docker-server3 ~]# docker exec -it 5e82ea0e65f0 /bin/bash

注意有的容器可能没有bash终端,可以尝试使用shell终端,即docker exec -it 5e82ea0e65f0 /bin/sh

就可以正在容器内进行一些测试操作

[root@5e82ea0e65f0 /]# ps -ef

UID         PID   PPID  C STIME TTY          TIME CMD
root          1      0  0 11:51 pts/0    00:00:00 /bin/bash
root         14      0  0 11:53 pts/1    00:00:00 /bin/bash
root         27     14  0 11:54 pts/1    00:00:00 ps -ef

[root@5e82ea0e65f0 /]# curl www.baidu.com

<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

[root@5e82ea0e65f0 /]# yum -y install net-tools

[root@5e82ea0e65f0 /]# ifconfig

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.0.2  netmask 255.255.255.0  broadcast 192.168.0.255
        ether 02:42:c0:a8:00:02  txqueuelen 0  (Ethernet)
        RX packets 2079  bytes 25943446 (24.7 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 2048  bytes 115915 (113.1 KiB)
        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

发现ip的网段是192.168.0.0/16

查看dockers配置

[root@5e82ea0e65f0 /]# exit

[root@docker-server3 ~]# cat /etc/docker/daemon.json

{
"log-driver":"journald",
"bip":"192.168.0.1/24"
}

2.2 docker的终端运行进程

每个docker容器都有一个默认的进程,但是这个进程拥有最低权限,可以覆盖掉

例如安装httpd测试

[root@docker-server3 ~]# docker run -d httpd:2.4

c57bbb0cae70ea529fbddec7de895cfd8865a55fd1cafb39e81e144dbccceb47

[root@docker-server3 ~]# docker run -it httpd:2.4 /bin/bash

root@11494f95ef19:/usr/local/apache2#

另开一个终端查看

[root@docker-server3 ~]# docker ps -a

CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS                      PORTS               NAMES
11494f95ef19        httpd:2.4           "/bin/bash"              24 seconds ago       Up 23 seconds               80/tcp              serene_cannon
c57bbb0cae70        httpd:2.4           "httpd-foreground"       35 seconds ago       Up 34 seconds               80/tcp              serene_williamson

COMMAND就是容器的终端进程,但是看到第一个进程是我们指定的/bin/bash,覆盖了默认进程httpd-foreground

2.3 运行一个redis测试

[root@docker-server3 ~]# docker run -d redis:4.0

Unable to find image 'redis:4.0' locally
4.0: Pulling from library/redis
8ec398bc0356: Pull complete 
da01136793fa: Pull complete 
cf1486a2c0b8: Pull complete 
94baf980b8df: Pull complete 
08ee3ec1a85f: Pull complete 
9990996bca2f: Pull complete 
Digest: sha256:e4adaff7466861d44c2d21178c5b8e8fa7d812172b9747071b08502b37e6ea2a
Status: Downloaded newer image for redis:4.0
acd538e93dec6de676610894ee5733caf7f23793d9b15ad72c2447c7436eabd2

[root@docker-server3 ~]# docker ps -a

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
acd538e93dec        redis:4.0           "docker-entrypoint.s…"   14 seconds ago      Up 13 seconds       6379/tcp            zen_raman
5e82ea0e65f0        centos:7            "/bin/bash"              24 minutes ago      Up 23 minutes                           romantic_lewin

[root@docker-server3 ~]# docker inspect acd538e93dec|grep IP

"LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "192.168.0.3",
            "IPPrefixLen": 24,
            "IPv6Gateway": "",
                    "IPAMConfig": null,
                    "IPAddress": "192.168.0.3",
                    "IPPrefixLen": 24,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,

安装一个redis-cli客户端的容器

进入查看操作

https://hub.docker.com/r/goodsmileduck/redis-cli

[root@docker-server3 ~]# docker run -it goodsmileduck/redis-cli:latest /bin/sh

Unable to find image 'goodsmileduck/redis-cli:latest' locally
latest: Pulling from goodsmileduck/redis-cli
050382585609: Pull complete 
ff9fae49e01a: Pull complete 
Digest: sha256:dbe86d99f417fd3d18c06ecdadc6f473300e365c711de6b3da7f4598ee6feb1f
Status: Downloaded newer image for goodsmileduck/redis-cli:latest

 / # redis-cli -h 192.168.0.3 -p 6379 info

# Server
redis_version:4.0.14
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:198fbb2e6c7e2b25
redis_mode:standalone
os:Linux 3.10.0-957.27.2.el7.x86_64 x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:8.3.0
process_id:1
run_id:659feb59d1a9210008d21e67952b9c018cb14a46
tcp_port:6379
uptime_in_seconds:1411
uptime_in_days:0
hz:10
lru_clock:737553
executable:/data/redis-server
config_file:

# Clients
connected_clients:1
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0

# Memory
used_memory:849352
used_memory_human:829.45K
used_memory_rss:7974912
used_memory_rss_human:7.61M
used_memory_peak:849352
used_memory_peak_human:829.45K
used_memory_peak_perc:100.12%
used_memory_overhead:836126
used_memory_startup:786488
used_memory_dataset:13226
used_memory_dataset_perc:21.04%
total_system_memory:1907953664
total_system_memory_human:1.78G
used_memory_lua:37888
used_memory_lua_human:37.00K
maxmemory:0
maxmemory_human:0B
maxmemory_policy:noeviction
mem_fragmentation_ratio:9.39
mem_allocator:jemalloc-4.0.3
active_defrag_running:0
lazyfree_pending_objects:0

# Persistence
loading:0
rdb_changes_since_last_save:0
rdb_bgsave_in_progress:0
rdb_last_save_time:1577794446
rdb_last_bgsave_status:ok
rdb_last_bgsave_time_sec:-1
rdb_current_bgsave_time_sec:-1
rdb_last_cow_size:0
aof_enabled:0
aof_rewrite_in_progress:0
aof_rewrite_scheduled:0
aof_last_rewrite_time_sec:-1
aof_current_rewrite_time_sec:-1
aof_last_bgrewrite_status:ok
aof_last_write_status:ok
aof_last_cow_size:0

# Stats
total_connections_received:2
total_commands_processed:1
instantaneous_ops_per_sec:0
total_net_input_bytes:31
total_net_output_bytes:10163
instantaneous_input_kbps:0.00
instantaneous_output_kbps:0.00
rejected_connections:0
sync_full:0
sync_partial_ok:0
sync_partial_err:0
expired_keys:0
expired_stale_perc:0.00
expired_time_cap_reached_count:0
evicted_keys:0
keyspace_hits:0
keyspace_misses:0
pubsub_channels:0
pubsub_patterns:0
latest_fork_usec:0
migrate_cached_sockets:0
slave_expires_tracked_keys:0
active_defrag_hits:0
active_defrag_misses:0
active_defrag_key_hits:0
active_defrag_key_misses:0

# Replication
role:master
connected_slaves:0
master_replid:2f59d8dd98d882302c7da6d302faa6aa0857979a
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0

# CPU
used_cpu_sys:1.25
used_cpu_user:1.14
used_cpu_sys_children:0.00
used_cpu_user_children:0.00

# Cluster
cluster_enabled:0

也可以在外面执行,指令执行完容器就退出

[root@docker-server3 ~]# docker run -it goodsmileduck/redis-cli:latest redis-cli -h 192.168.0.3 -p 6379 info

会得到上面一个相同的结果,但是容器执行完,得到结果后,容器就退出

[root@docker-server3 ~]# docker ps -a

CONTAINER ID        IMAGE                            COMMAND                  CREATED              STATUS                          PORTS               NAMES
66886f9eca2f        goodsmileduck/redis-cli:latest   "redis-cli -h 192.16…"   About a minute ago   Exited (0) About a minute ago                       cocky_cerf
d798dd31871d        goodsmileduck/redis-cli:latest   "redis-cli -h 192.16…"   About a minute ago   Exited (0) About a minute ago                       zealous_jackson
281468c747b3        goodsmileduck/redis-cli:latest   "/bin/sh"                5 minutes ago        Exited (0) About a minute ago                       musing_wiles
acd538e93dec        redis:4.0                        "docker-entrypoint.s…"   28 minutes ago       Up 28 minutes                   6379/tcp            zen_raman
5e82ea0e65f0        centos:7                         "/bin/bash"              52 minutes ago       Up 50 minutes                                       romantic_lewin

删除掉不必要的容器

[root@docker-server3 ~]# docker rm 66886f9eca2f d798dd31871d 281468c747b3

[root@docker-server3 ~]# docker ps -a

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
acd538e93dec        redis:4.0           "docker-entrypoint.s…"   33 minutes ago      Up 33 minutes       6379/tcp            zen_raman
5e82ea0e65f0        centos:7            "/bin/bash"              58 minutes ago      Up 56 minutes                           romantic_lewin

短任务执行后,退出就删除容器

[root@docker-server3 ~]# docker run -it --rm goodsmileduck/redis-cli:latest redis-cli -h 192.168.0.3 -p 6379 info

[root@docker-server3 ~]# docker ps -a

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
acd538e93dec        redis:4.0           "docker-entrypoint.s…"   35 minutes ago      Up 35 minutes       6379/tcp            zen_raman
5e82ea0e65f0        centos:7            "/bin/bash"              59 minutes ago      Up 58 minutes                           romantic_lewin

容器执行完,已经被删除


 博主声明:本文的内容来源主要来自誉天教育晏威老师,由本人实验完成操作验证,需要的博友请联系誉天教育(http://www.yutianedu.com/),获得官方同意或者晏老师(https://www.cnblogs.com/breezey/)本人同意即可转载,谢谢!

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
在线直播报名
返回顶部
顶部