初学docker容器

Posted 咸鱼王变身

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了初学docker容器相关的知识,希望对你有一定的参考价值。

docker是什么

  • docker是一种轻量级的虚拟机
  • 在linux容器中运行应用并且开源

docker与虚拟机的区别

不同点容器虚拟机
启动速度上秒级分钟级
运行性能上接近原生(直接运行在内核中的90%)50%左右的损失
数量依据进程,可以有很多进程成百上千个一般几十台(操作系统级别)
隔离进程级别系统级别(更彻底的隔离)
磁盘占用MBGB(操作系统的镜像一般在几个G左右)
操作系统主要支持linux几乎所有系统
封装程度只打包项目代码和依赖关系,共享宿主机内核完整的操作系统,与宿主机互相隔离

同时docker解决了vm的环境孤岛问题,docker可以自定义传递参数

docker使用场景

  • 用来打包应用程序简化部署
  • 脱离底层硬件任意迁移
  • 持续集成和持续交付(CI/CD):开发到测试发布
  • 部署微服务
  • 提供PAAS产品

docker的原理

cgroup资源控制与namespace名称空间结合控制管理6个名称空间资源实现完整隔离/完全隔离

  • mount :文件系统,挂载点
  • user :操作进程的用户和用户组
  • pid :进程编号
  • uts :主机名和主机域
  • ipc:信号量,消息队列,共享内存(不同的应用调用内存资源时使用不同的内存空间)
  • net:网络设备,网络协议栈,端口等
    该mount命名空间:管理文件系统挂载点
    该pid命名空间:进程隔离(pid:进程id)
    该uts命名空间:隔离内核和版本标识符(uts:Unix时间共享系统)
    该ipc命名空间:管理访问ipc资源(ipc:进程间互相通信)
    该net命名空间:管理网络接口(net:网络)

docker三个统一和docker三大组件

docker把容器化技术做成了标准化平台

  • docker引擎统一了基础设施环境—》docker环境
  • docker引擎统一了程序打包方式—》docker镜像
  • docker引擎统一了程序部署方式—》docker容器–》基于镜像,运行为容器(可运行的环境)
    实现了一次构建,多次,多处使用
    三大组件:
  • 镜像:作为模板,一组资源的集合,包含了应用程序软件包,应用程序相关的依赖包,运行应用程序所需要的基础环境
  • 容器:运行状态/运行时状态,基于镜像的一种运行时状态
  • 仓库:存放镜像模板的地方,仓库分类:公共仓库–》docker hub,私有仓库–》registry harbor

docker引擎

docker引擎具有以下主要组件的C/S应用程序(客户端-服务器)
server端:服务器是一种长期运行的程序,成为守护进程
client端:REST API指定程序可以用来与守护程序进行通信并指示其操作的接口

docker-server配置文件

在/etc/docker/daemon.json中配置

{
"graph":"/data/docker",			//数据目录
"storage-driver":"overlay2",		//存储引擎
"insecure-registries" ["registry.access.redhat.com","quary.io"]	//私有仓库
"registry-mirrors": ["https://cn90fxk6.mirror.aliyuncs.com"]	//镜像加速
"bip":"172.17.0.1/24",			//docker网络
"exec-opts":["native.cgroupdriver=systemd"],		//启动时的额外参数
"live-restore":true			//当docker容器存储引擎挂了后,使用docker跑起来的容器还能运行
}

docker的部署(20版)

  • 安装依赖包
[root@node1 nginx]# yum install -y yum-utils device-mapper-persistent-data lvm2

  • 设置阿里云镜像源
[root@node1 yum.repos.d]# yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

  • 安装docker-ce社区版
[root@node1 yum.repos.d]# yum install -y docker-ce

  • 然后启动docker
[root@node1 yum.repos.d]# systemctl enable docker
[root@node1 yum.repos.d]# systemctl start docker

  • 设置镜像加速,去阿里云的镜像加速分类

  • 将底下的代码直接复制到命令行就可以了,要选对应的操作系统

  • 查看是否设置成功

[root@node1 yum.repos.d]# vim /etc/docker/daemon.json 
{
  "registry-mirrors": ["https://cn90fxk6.mirror.aliyuncs.com"]
}

docker镜像操作

[root@node1 yum.repos.d]# 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.			//由服务端的守护进程从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/

  • 查询docker版本
[root@node1 yum.repos.d]# docker version 
Client: Docker Engine - Community
 Version:           20.10.8
 API version:       1.41
 Go version:        go1.16.6
 Git commit:        3967b7d
 Built:             Fri Jul 30 19:55:49 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.8
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.16.6
  Git commit:       75249d8
  Built:            Fri Jul 30 19:54:13 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.9
  GitCommit:        e25210fe30a0a703442421b0f60afac609f950a3
 runc:
  Version:          1.0.1
  GitCommit:        v1.0.1-0-g4144b63
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

[root@node1 yum.repos.d]# 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.6.1-docker)
  scan: Docker Scan (Docker Inc., v0.8.0)

Server:
 Containers: 14
  Running: 5
  Paused: 0
  Stopped: 9
 Images: 63
 Server Version: 20.10.8
 Storage Driver: overlay2
  Backing Filesystem: xfs
  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.runc.v2 io.containerd.runtime.v1.linux runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: e25210fe30a0a703442421b0f60afac609f950a3
 runc version: v1.0.1-0-g4144b63
 init version: de40ad0
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 3.10.0-957.el7.x86_64
 Operating System: CentOS Linux 7 (Core)
 OSType: linux
 Architecture: x86_64
 CPUs: 4
 Total Memory: 5.712GiB
 Name: node1
 ID: QL6Y:HC6L:E57G:UWHJ:E7FY:J47A:YF6Z:GLL2:DETH:DY4C:STNH:ZGFS
 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://cn90fxk6.mirror.aliyuncs.com/
 Live Restore Enabled: false

WARNING: bridge-nf-call-iptables is disabled
WARNING: bridge-nf-call-ip6tables is disabled

  • 搜索镜像
[root@node1 yum.repos.d]# docker search nginx
NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
nginx                             Official build of Nginx.                        15420     [OK]       
jwilder/nginx-proxy               Automated Nginx reverse proxy for docker con…   2063                 [OK]
richarvey/nginx-php-fpm           Container running Nginx + PHP-FPM capable of…   816                  [OK]
jc21/nginx-proxy-manager          Docker container for managing Nginx proxy ho…   240                  
linuxserver/nginx                 An Nginx container, brought to you by LinuxS…   152                  
tiangolo/nginx-rtmp               Docker image with Nginx using the nginx-rtmp…   141                  [OK]
jlesage/nginx-proxy-manager       Docker container for Nginx Proxy Manager        135                  [OK]
alfg/nginx-rtmp                   NGINX, nginx-rtmp-module and FFmpeg from sou…   106                  [OK]
jasonrivers/nginx-rtmp            Docker images to host RTMP streams using NGI…   92                   [OK]
nginxdemos/hello                  NGINX webserver that serves a simple page co…   72                   [OK]
privatebin/nginx-fpm-alpine       PrivateBin running on an Nginx, php-fpm & Al…   56                   [OK]
nginx/nginx-ingress               NGINX and  NGINX Plus Ingress Controllers fo…   55                   
nginxinc/nginx-unprivileged       Unprivileged NGINX Dockerfiles                  47                   
staticfloat/nginx-certbot         Opinionated setup for automatic TLS certs lo…   24                   [OK]
nginxproxy/nginx-proxy            Automated Nginx reverse proxy for docker con…   20                   
schmunk42/nginx-redirect          A very simple container to redirect HTTP tra…   19                   [OK]
nginx/nginx-prometheus-exporter   NGINX Prometheus Exporter for NGINX and NGIN…   19                   
centos/nginx-112-centos7          Platform for running nginx 1.12 or building …   15                   
centos/nginx-18-centos7           Platform for running nginx 1.8 or building n…   13                   
bitwarden/nginx                   The Bitwarden nginx web server acting as a r…   11                   
flashspys/nginx-static            Super Lightweight Nginx Image                   10                   [OK]
mailu/nginx                       Mailu nginx frontend                            9                    [OK]
sophos/nginx-vts-exporter         Simple server that scrapes Nginx vts stats a…   7                    [OK]
ansibleplaybookbundle/nginx-apb   An APB to deploy NGINX                          2                    [OK]
wodby/nginx                       Generic nginx                                   1     
[root@node1 yum.repos.d]# docker search centos:7
NAME                                                DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
benwang6/tedu-jdk                                   oracle jdk 8u281 centos:7 JAVA_HOME=/usr/jdk…   5                    
vikingco/python                                     Python Stack Docker Base Image: Based on cen…   1                    
sndnvaps/docker-golang                              build latest golang in centos:7                 1                    [OK]
legerete/nginx-php71                                LA[->]P - Centos:7 + Nginx + PHP 7.1            1                    [OK]
peltikalle/basepython                               Base image with Centos:7 and Python 3.5.2       1                    [OK]
mjstealey/mariadb-galera                            MariaDB Galera cluster in Docker - based fro…   1                    [OK]
acktsw/java                                         oracle jdk 8u171 , centos:7,  timeZone:+8, e…   0                    [OK]
macedigital/nodejs                                  Latest NodeJS for CentOS:7                      0                    [OK]
grossws/nginx                                       nginx (mainline) on grossws/centos:7            0                    [OK]
europeanspallationsource/oracle-jdk-maven-jenkins   ICS oracle-jdk + maven + jenkins users image…   0                    
pbieberstein/acic-findr                             CentOS:7 with dependencies to run 'Findr' (h…   0                    [OK]
sjoeboo/rbenv                                       Simple base container from CentOS:7 w/ rbenv…   0                    [OK]
alvintz/centos                                      centos:7.2.1511                                 0                    [OK]
geomatikk/centos                                    FROM centos:7 with maven 3.6.1 and openjdk-10                    
waffleimage/centos7                                 Centos:7 with systemd and ssh running           0                    
cristo/netacuity                                    Docker image on Centos:7 to run NetAcuity       0                    [OK]
badwolf/centos                                      from official centos:7 add gcc,gcc++,make,vi    0                    [OK]
mesosphere/freeipa-server                           A freeIPA v4.3 container based on centos:7.0                    
acktsw/centos                                       centos:7                                        0                    [OK]
bbania/centos                                       Build image based on centos:7                   0                    
a2747/centos7                                       derivative images from centos:7                 0                    
21plus2/server-jre                                  Dockerimage base on centos:7 with server-jre    0                    [OK]
europeanspallationsource/oracle-jdk-maven           ICS oracle-jdk + maven image based on centos…   0                    
qiyue/mycat                                         centos:7 + jdk:1.8 + mycat                      0                    
weihoop/mysql                                       基于weihoop/centos:7.4.1708制作          
  • 下载镜像
[root@node1 yum.repos.d]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
a330b6cecb98: Pull complete 
5ef80e6f29b5: Pull complete 
f699b0db74e3: Pull complete 
0f701a34c55e: Pull complete 
3229dce7b89c: Pull complete 
ddb78cb2d047: Pull complete 
Digest: sha256:a05b0cdd4fc1be3b224ba9662ebdf98fe44c09c0c9215b45f84344c12867002e
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
[root@node1 yum.repos.d]# docker images			//查看镜像列表
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
nginx         latest    822b7ec2aaf2   2 days ago     133MB

  • 获取镜像信息
[root@node1 yum.repos.d]# docker inspect 822b7ec2aaf2
[
    {
        "Id": "sha256:822b7ec2aaf2122b8f80f9c7f45ca62ea3379bf33af4e042b67aafbf6eac1941",
        "RepoTags": [
            "nginx:latest"
        ],
        "RepoDigests": [
            "nginx@sha256:a05b0cdd4fc1be3b224ba9662ebdf98fe44c09c0c9215b45f84344c12867002e"
        ],
        "Parent": "",
        "Comment": "",
        "Created": "2021-09-03T07:40:16.355730864Z",
        "Container": "367d32086ac12447d36e75c9b7acbe1b5156a34a91370b9200e68783be75506c",
        "ContainerConfig": {
            "Hostname": "367d32086ac1",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.21.1",
                "NJS_VERSION=0.6.1",
                "PKG_RELEASE=1~buster"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "#(nop) ",
                "CMD [\\"nginx\\" \\"-g\\" \\"daemon off;\\"]"
            ],
            "Image": "sha256:d4315787e4fec867791beba140dd0e44f657cb6e4a9d75c676c7946089c20da9",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],

  • 添加镜像标签
[root@node1 yum.repos.d]# docker images 
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
nginx         123       822b7ec2aaf2   2 days ago     133MB
nginx         latest    822b7ec2aaf2   2 days ago     133MB

  • 删除镜像
[root@node1 yum.repos.d]# docker rmi nginx:123
Untagged: nginx:123
[root@node1 yum.repos.d]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
nginx         latest    822b7ec2aaf2   2 days ago     133MB

  • 导出镜像
[root@node1 ~]# docker save -o nginx_images nginx:latest 
[root@node1 ~]# ls
12   1.sh   2333  45               apps         initial-setup-ks.cfg       ks.cfg  nginx_images  模板  图片  下载  桌面
123  1.txt  234   anaconda-ks.cfg  docker_home  jdk-8u91-linux-x64.tar.gz  nginx   公共          视频  文档  音乐

  • 导入镜像,将原有的先删除再导入
[root@node1 ~]# docker load < nginx_images 
d000633a5681: Loading layer [==================================================>]  72.53MB/72.53MB
63b5f2c0d071: Loading layer [==================================================>]  64.86MB/64.86MB
875b5b50454b: Loading layer [==================================================>]  3.072kB/3.072kB
ed94af62a494: Loading layer [==================================================>]  4.096kB/4.096kB
8e58314e4a4f: Loading layer [==================================================>]  3.584kB/3.584kB
d47e4d19ddec: Loading layer [==================================================>]  7.168kB/7.168kB
Loaded image: nginx:latest
[root@node1 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
nginx         latest    822b7ec2aaf2   2 days ago     133MB

  • 查询容器
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED       STATUS       PORTS                                         NAMES

  • 创建容器
[root@node1 ~]# docker create -it nginx:latest /bin/bash
9eade02412f5ecc3e9e2006de2f59845ca50ed4a52741ad9f0a8fb43ce5086f3
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS       PORTS                                         NAMES
9eade02412f5   nginx:latest   "/docker-entrypoint.…"   3 seconds ago   Created                                                    keen_chatterjee
//-i是让容器的标准输入保持打开
//-t是分配一个伪终端
//-d是后台守护进程的方式运行
  • 启动容器
[root@node1 ~]# docker start 9eade02412f5
9eade02412f5
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED              STATUS         PORTS                                         NAMES
9eade02412f5   nginx:latest   "/docker-entrypoint.…"   About a minute ago   Up 2 seconds   80/tcp                                        keen_chatterjee

  • 一次性执行来启动容器
[root@node1 ~]# docker run centos:7 /usr/bin/bash -c ls /
anaconda-post.log
bin
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var

  • 停止容器
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS                       PORTS                                         NAMES
9eade02412f5   nginx:latest   "/docker-entrypoint.…"   4 minutes ago    Exited Docker删除报错:Error response from daemon: conflict: unable to delete 08b152afcfae (must be forced)(代码片段

通过运行一个tomcat容器来记录下初学docker常用的几个命令---容器篇

Docker初学乍练之单主机网络

通过运行一个tomcat容器来记录下初学docker常用的几个命令---镜像篇

Docker初学

将 Docker 容器限制为单个 cpu 核心