一 容器分类

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

服务类容器,如 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
: 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: "/bin/bash" About a minute ago Exited () 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: "/bin/bash" About a minute ago Up 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 : pts/ :: /bin/bash
root : pts/ :: /bin/bash
root : pts/ :: ps -ef

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

<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-><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=<UP,BROADCAST,RUNNING,MULTICAST>  mtu
inet 192.168.0.2 netmask 255.255.255.0 broadcast 192.168.0.255
ether ::c0:a8:: txqueuelen (Ethernet)
RX packets bytes (24.7 MiB)
RX errors dropped overruns frame
TX packets bytes (113.1 KiB)
TX errors dropped overruns carrier collisions lo: flags=<UP,LOOPBACK,RUNNING> mtu
inet 127.0.0.1 netmask 255.0.0.0
loop txqueuelen (Local Loopback)
RX packets bytes (0.0 B)
RX errors dropped overruns frame
TX packets bytes (0.0 B)
TX errors dropped overruns carrier collisions

发现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" seconds ago Up seconds /tcp serene_cannon
c57bbb0cae70 httpd:2.4 "httpd-foreground" seconds ago Up seconds /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…" seconds ago Up seconds /tcp zen_raman
5e82ea0e65f0 centos: "/bin/bash" minutes ago Up minutes romantic_lewin

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

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

安装一个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
: 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.
redis_git_sha1:
redis_git_dirty:
redis_build_id:198fbb2e6c7e2b25
redis_mode:standalone
os:Linux 3.10.-957.27..el7.x86_64 x86_64
arch_bits:
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:8.3.
process_id:
run_id:659feb59d1a9210008d21e67952b9c018cb14a46
tcp_port:
uptime_in_seconds:
uptime_in_days:
hz:
lru_clock:
executable:/data/redis-server
config_file: # Clients
connected_clients:
client_longest_output_list:
client_biggest_input_buf:
blocked_clients: # Memory
used_memory:
used_memory_human:.45K
used_memory_rss:
used_memory_rss_human:7.61M
used_memory_peak:
used_memory_peak_human:.45K
used_memory_peak_perc:100.12%
used_memory_overhead:
used_memory_startup:
used_memory_dataset:
used_memory_dataset_perc:21.04%
total_system_memory:
total_system_memory_human:.78G
used_memory_lua:
used_memory_lua_human:.00K
maxmemory:
maxmemory_human:0B
maxmemory_policy:noeviction
mem_fragmentation_ratio:9.39
mem_allocator:jemalloc-4.0.
active_defrag_running:
lazyfree_pending_objects: # Persistence
loading:
rdb_changes_since_last_save:
rdb_bgsave_in_progress:
rdb_last_save_time:
rdb_last_bgsave_status:ok
rdb_last_bgsave_time_sec:-
rdb_current_bgsave_time_sec:-
rdb_last_cow_size:
aof_enabled:
aof_rewrite_in_progress:
aof_rewrite_scheduled:
aof_last_rewrite_time_sec:-
aof_current_rewrite_time_sec:-
aof_last_bgrewrite_status:ok
aof_last_write_status:ok
aof_last_cow_size: # Stats
total_connections_received:
total_commands_processed:
instantaneous_ops_per_sec:
total_net_input_bytes:
total_net_output_bytes:
instantaneous_input_kbps:0.00
instantaneous_output_kbps:0.00
rejected_connections:
sync_full:
sync_partial_ok:
sync_partial_err:
expired_keys:
expired_stale_perc:0.00
expired_time_cap_reached_count:
evicted_keys:
keyspace_hits:
keyspace_misses:
pubsub_channels:
pubsub_patterns:
latest_fork_usec:
migrate_cached_sockets:
slave_expires_tracked_keys:
active_defrag_hits:
active_defrag_misses:
active_defrag_key_hits:
active_defrag_key_misses: # Replication
role:master
connected_slaves:
master_replid:2f59d8dd98d882302c7da6d302faa6aa0857979a
master_replid2:
master_repl_offset:
second_repl_offset:-
repl_backlog_active:
repl_backlog_size:
repl_backlog_first_byte_offset:
repl_backlog_histlen: # 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:

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

[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 () About a minute ago cocky_cerf
d798dd31871d goodsmileduck/redis-cli:latest "redis-cli -h 192.16…" About a minute ago Exited () About a minute ago zealous_jackson
281468c747b3 goodsmileduck/redis-cli:latest "/bin/sh" minutes ago Exited () About a minute ago musing_wiles
acd538e93dec redis:4.0 "docker-entrypoint.s…" minutes ago Up minutes /tcp zen_raman
5e82ea0e65f0 centos: "/bin/bash" minutes ago Up 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…" minutes ago Up minutes /tcp zen_raman
5e82ea0e65f0 centos: "/bin/bash" minutes ago Up 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…" minutes ago Up minutes /tcp zen_raman
5e82ea0e65f0 centos: "/bin/bash" minutes ago Up minutes romantic_lewin

容器执行完,已经被删除


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

DOCKER学习_008:Docker容器的运行最佳实践的更多相关文章

  1. Windows10下的docker安装与入门 (三) 创建自己的docker镜像并且在容器中运行它

    Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化.容器是完全使用沙箱机制,相互之间不会有任何 ...

  2. Docker学习之Docker容器基本使用

    Docker学习之Docker容器基本使用 新建容器并启动 命令格式:docker run --options repository:tag 后台运行 命令格式:-d 已存在的容器相关操作 启动:do ...

  3. Docker学习之Docker镜像基本使用

    Docker学习之Docker镜像基本使用 获取镜像 命令格式:docker pull [选项] [Docker Registry 地址[:端口号]/]仓库名[:标签] 例如: docker pull ...

  4. Docker学习笔记 — Docker私有仓库搭建

    Docker学习笔记 — Docker私有仓库搭建   目录(?)[-] 环境准备 搭建私有仓库 测试 管理仓库中的镜像 查询 删除 Registry V2   和Mavan的管理一样,Dockers ...

  5. 8.云原生之Docker容器镜像构建最佳实践浅析

    转载自:https://www.bilibili.com/read/cv15220861/?from=readlist 本章目录 0x02 Docker 镜像构建最佳实践浅析 1.Dockerfile ...

  6. Docker学习笔记 - Docker容器内部署redis

    Docker学习笔记(2-4)Docker应用实验-redist server 和client的安装使用 一.获取redis容器(含客户端和服务端) 二.创建服务端容器 1.在终端A中运行redis- ...

  7. Docker学习-安装,配置,运行

    Docker继续学习 2019年12月15日23:15:36 第二次学习docker Docker三个重要概念: 镜像 就是一个模板(类似一个Java类) 容器 容器是用镜像创建的运行实例. 仓库 仓 ...

  8. Docker学习笔记 - Docker容器之间的连接

    学习目标: 容器之间可以相互连接访问:: --link redis:redisAlias 准备工作 FROM ubuntu:14.04 RUN apt-get install -y ping RUN  ...

  9. Docker学习之3——容器

    容器(Container) 容器介绍: docker是通过容器来运行业务的,就像运行一个kvm虚拟机是一样的.容器其实就是从镜像创建的一个实例. 我们可以对容器进行增删改查,容器之间也是相互隔离的.和 ...

随机推荐

  1. 2019-6-23-WPF-获得当前输入法语言区域

    title author date CreateTime categories WPF 获得当前输入法语言区域 lindexi 2019-06-23 11:51:21 +0800 2018-10-12 ...

  2. Java练习 SDUT-1580_闰年

    闰年 Time Limit: 1000 ms Memory Limit: 32768 KiB Problem Description 时间过得真快啊,又要过年了,同时,我们的人生也增长了一年的阅历,又 ...

  3. auto uninstaller密钥激活码破解注册机ver 8.8.58

    auto uninstaller密钥破解注册机ver 8.8.58 楼主分享几个auto uninstaller密钥破解注册机,可以用于auto uninstaller 8.8.58 .因为每个版本的 ...

  4. ModuleNotFoundError: No module named 'tools.nnwrap' pytorch 安装

    https://pytorch.org/get-started/locally/ pytorch 主页选择后安装

  5. @codeforces - 1187F@ Expected Square Beauty

    目录 @description@ @solution@ @accepted code@ @details@ @description@ 给定一个序列 x = {x1, x2, ..., xn},已知 ...

  6. day5_python之环境变量设置

    1.设置环境变量 import os,sys print(os.path.abspath(__file__)) #当前py文件的绝对路径 print(os.path.dirname(os.path.a ...

  7. H3C 常用接口和线缆

  8. gSOAP 使用

    1. wsdl2h 生成服务定义头文件 wsdl2h -o calc.h http://www.genivia.com/calc.wsdl 2. 从服务定义头文件calc.h生成客户端代码 soapc ...

  9. [转载] iptables 防火墙设置

    http://hongwei.im/iptables-setting-for-ubuntu-1304/ Iptables是一个防火墙,所有的Ubuntu官方发行版(Ubuntu,Kubuntu,Xub ...

  10. python 字符串方法isdigit()

    python isdigit() 方法检测字符串是否只有数字组成. 语法: isdigit()方法语法: str.isdigit() 参数:无 返回值: 如果字符串中只含有数字则返回True,否则返回 ...