您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
02-Docker基础用法
发布时间:2020-08-29 22:52:42编辑:雪饮阅读()
查找docker容器
Docker容器可以在https://hub.docker.com/中搜索,比如
安装docker
Docker需要centos7及以上
在centos7中他yum的repo仓库配置在extras中:
[root@localhost ~]# yum repolist
Loaded plugins: fastestmirror
base | 3.6 kB 00:00
extras | 2.9 kB 00:01
updates | 2.9 kB 00:00
(1/4): extras/7/x86_64/primary_db | 206 kB 00:01
(2/4): base/7/x86_64/group_gz | 153 kB 00:01
(3/4): updates/7/x86_64/primary_db | 4.5 MB 00:00:06
(4/4): base/7/x86_64/primary_db | 6.1 MB 00:00:23
Determining fastest mirrors
* base: mirrors.aliyun.com
* extras: mirrors.aliyun.com
* updates: mirrors.aliyun.com
repo id repo name status
base/7/x86_64 CentOS-7 - Base 10,070
extras/7/x86_64 CentOS-7 - Extras 413
updates/7/x86_64 CentOS-7 - Updates 1,125
repolist: 11,608
我们看看该repo
[root@localhost ~]# cat /etc/yum.repos.d/CentOS-Base.repo
# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client. You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#
[base]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#released updates
[updates]
name=CentOS-$releasever - Updates
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
我们搜索下我们目前仓库是否有docker
[root@localhost ~]# yum search docker
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.aliyun.com
* extras: mirrors.aliyun.com
* updates: mirrors.aliyun.com
==================================================================== N/S matched: docker =====================================================================
cockpit-docker.x86_64 : Cockpit user interface for Docker containers
docker-client.x86_64 : Client side files for Docker
docker-client-latest.x86_64 : Client side files for Docker
docker-common.x86_64 : Common files for docker and docker-latest
docker-distribution.x86_64 : Docker toolset to pack, ship, store, and deliver content
docker-latest-logrotate.x86_64 : cron job to run logrotate on Docker containers
docker-latest-v1.10-migrator.x86_64 : Calculates SHA256 checksums for docker layer content
docker-logrotate.x86_64 : cron job to run logrotate on Docker containers
docker-lvm-plugin.x86_64 : Docker volume driver for lvm volumes
docker-registry.x86_64 : Registry server for Docker
docker-v1.10-migrator.x86_64 : Calculates SHA256 checksums for docker layer content
pcp-pmda-docker.x86_64 : Performance Co-Pilot (PCP) metrics from the Docker daemon
podman-docker.noarch : Emulate Docker CLI using podman
python-docker-py.noarch : An API client for docker written in Python
python-docker-pycreds.noarch : Python bindings for the docker credentials store API
docker.x86_64 : Automates deployment of containerized applications
docker-latest.x86_64 : Automates deployment of containerized applications
docker-novolume-plugin.x86_64 : Block container starts with local volumes defined
oci-systemd-hook.x86_64 : OCI systemd hook for docker
oci-umount.x86_64 : OCI umount hook for docker
可见我们的docker是存在于仓库中的,并且版本还不算太旧,可能我的是centos7.3的原因,默认把包升级到1.13了
[root@localhost ~]# yum info docker
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.aliyun.com
* extras: mirrors.aliyun.com
* updates: mirrors.aliyun.com
Available Packages
Name : docker
Arch : x86_64
Epoch : 2
Version : 1.13.1
Release : 162.git64e9980.el7.centos
Size : 18 M
Repo : extras/7/x86_64
Summary : Automates deployment of containerized applications
URL : https://github.com/docker/docker
License : ASL 2.0
Description : Docker is an open-source engine that automates the deployment of any
: application as a lightweight, portable, self-sufficient container that will
: run virtually anywhere.
:
: Docker containers can encapsulate any payload, and will run consistently on
: and between virtually any server. The same container that a developer builds
: and tests on a laptop will run at scale, in production*, on VMs, bare-metal
: servers, OpenStack clusters, public instances, or combinations of the above.
这个版本也正好是我所想要的版本,接下来我们只需要一条命令就安装了docker,centos7的早期版本中曾经要更换为清华大学等高速源才可以,不然会很慢的,而且安装时是yum install docker-ce。。,而我们这里只需要一套命令:
[root@localhost ~]# yum install docker
配置加速节点
因为docker毕竟是国外的产物,配置一个国内加速节点有时候也是有必要的
[root@localhost ~]# cat /etc/docker/daemon.json
{
"registry-mirrors":["https://registry.docker-cn.com"]
}
开启docker服务
首先要确保你的selinux是关闭的,若不是关闭的就需要关闭
[root@localhost ~]# cat /etc/sysconfig/selinux
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of three two values:
# targeted - Targeted processes are protected,
# minimum - Modification of targeted policy. Only selected processes are protected.
# mls - Multi Level Security protection.
SELINUXTYPE=targeted
然后可能你需要重启下系统,然后就可以开启docker服务了
[root@localhost ~]# systemctl start docker.service
查看docker版本信息
[root@localhost ~]# docker version
Client:
Version: 1.13.1
API version: 1.26
Package version: docker-1.13.1-162.git64e9980.el7.centos.x86_64
Go version: go1.10.3
Git commit: 64e9980/1.13.1
Built: Wed Jul 1 14:56:42 2020
OS/Arch: linux/amd64
Server:
Version: 1.13.1
API version: 1.26 (minimum version 1.12)
Package version: docker-1.13.1-162.git64e9980.el7.centos.x86_64
Go version: go1.10.3
Git commit: 64e9980/1.13.1
Built: Wed Jul 1 14:56:42 2020
OS/Arch: linux/amd64
Experimental: false
Docker的info
[root@localhost ~]# docker info
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 0
Server Version: 1.13.1
Storage Driver: overlay2
Backing Filesystem: xfs
Supports d_type: true
Native Overlay Diff: false
Logging Driver: journald
Cgroup Driver: systemd
Plugins:
Volume: local
Network: bridge host macvlan null overlay
Swarm: inactive
Runtimes: docker-runc runc
Default Runtime: docker-runc
Init Binary: /usr/libexec/docker/docker-init-current
containerd version: (expected: aa8187dbd3b7ad67d8e5e3a15115d3eef43a7ed1)
runc version: 66aedde759f33c190954815fb765eedc1d782dd9 (expected: 9df8b306d01f59d3a8029 be411de015b7304dd8f)
init version: fec3683b971d9c3ef73f284f176672c44b448662 (expected: 949e6facb77383876aeff 8a6944dde66b3089574)
Security Options:
seccomp
WARNING: You're not using the default seccomp profile
Profile: /etc/docker/seccomp.json
Kernel Version: 3.10.0-514.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
Number of Docker Hooks: 3
CPUs: 1
Total Memory: 984.8 MiB
Name: localhost.localdomain
ID: TESE:X6ZC:LAI2:G5MW:EQWB:VFS3:X7YR:HFZP:RKKV:ZZS2:GZK7:ZYOU
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Experimental: false
Insecure Registries:
127.0.0.0/8
Registry Mirrors:
https://registry.docker-cn.com
Live Restore Enabled: false
Registries: docker.io (secure)
从上面标红的地方可以看到我们配置的加速节点生效了
搜索一个docker容器
刚才我们可以在一个docker的hub网站上搜索到一个docker容器,现在我们命令行里面也可以
[root@localhost ~]# docker search nginx
INDEX NAME DESCRIPTION STARS OFFICIAL AUTOMATED
docker.io docker.io/nginx Official build of Nginx. 13667 [OK]
docker.io docker.io/jwilder/nginx-proxy Automated Nginx reverse proxy for docker c... 1866 [OK]
docker.io docker.io/richarvey/nginx-php-fpm Container running Nginx + PHP- FPM capable ... 782 [OK]
docker.io docker.io/linuxserver/nginx An Nginx container, brought to you by Linu... 127
docker.io docker.io/bitnami/nginx Bitnami nginx Docker Image 89 [OK]
docker.io docker.io/tiangolo/nginx-rtmp Docker image with Nginx using the nginx-rt... 88 [OK]
docker.io docker.io/jc21/nginx-proxy-manager Docker container for managing Nginx proxy ... 82
docker.io docker.io/alfg/nginx-rtmp NGINX, nginx-rtmp-module and F Fmpeg from s... 75 [OK]
docker.io docker.io/nginxdemos/hello NGINX webserver that serves a simple page ... 59 [OK]
docker.io docker.io/jlesage/nginx-proxy-manager Docker container for Nginx Pro xy Manager 53 [OK]
docker.io docker.io/nginx/nginx-ingress NGINX Ingress Controller for K ubernetes 40
docker.io docker.io/privatebin/nginx-fpm-alpine PrivateBin running on an Nginx , php-fpm & ... 32 [OK]
docker.io docker.io/schmunk42/nginx-redirect A very simple container to red irect HTTP t... 19 [OK]
docker.io docker.io/nginxinc/nginx-unprivileged Unprivileged NGINX Dockerfiles 17
docker.io docker.io/nginx/nginx-prometheus-exporter NGINX Prometheus Exporter 15
docker.io docker.io/centos/nginx-112-centos7 Platform for running nginx 1.1 2 or buildin... 14
docker.io docker.io/centos/nginx-18-centos7 Platform for running nginx 1.8 or building... 13
docker.io docker.io/raulr/nginx-wordpress Nginx front-end for the offici al wordpress... 13 [OK]
docker.io docker.io/bitwarden/nginx The Bitwarden nginx web server acting as a... 7
docker.io docker.io/mailu/nginx Mailu nginx frontend 7 [OK]
docker.io docker.io/sophos/nginx-vts-exporter Simple server that scrapes Ngi nx vts stats... 7 [OK]
docker.io docker.io/bitnami/nginx-ingress-controller Bitnami Docker Image for NGINX Ingress Con... 6 [OK]
docker.io docker.io/flashspys/nginx-static Super Lightweight Nginx Image 6 [OK]
docker.io docker.io/ansibleplaybookbundle/nginx-apb An APB to deploy NGINX 1 [OK]
docker.io docker.io/wodby/nginx Generic nginx 1 [OK]
当然还是网页上搜索结果更友好,其详情页还可以看到tags即各种版本
下载docker镜像
[root@localhost ~]# docker image pull nginx:1.14-alpine
Trying to pull repository docker.io/library/nginx ...
1.14-alpine: Pulling from docker.io/library/nginx
bdf0201b3a05: Pull complete
3d0a573c81ed: Pull complete
8129faeb2eb6: Pull complete
3dc99f571daf: Pull complete
Digest: sha256:485b610fefec7ff6c463ced9623314a04ed67e3945b9c08d7e53a47f6d108dc7
Status: Downloaded newer image for docker.io/nginx:1.14-alpine
查看本地已下载的docker镜像列表
[root@localhost ~]# docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
docker.io/nginx 1.14-alpine 8a2fb25a19f5 16 months ago 16 MB
下载docker镜像(简写)
没有指定具体版本就是下载该镜像的最新版本
[root@localhost ~]# docker pull busybox
Using default tag: latest
Trying to pull repository docker.io/library/busybox ...
latest: Pulling from docker.io/library/busybox
61c5ed1cbdf8: Pull complete
Digest: sha256:4f47c01fa91355af2865ac10fef5bf6ec9c7f42ad2321377c21e844427972977
Status: Downloaded newer image for docker.io/busybox:latest
[root@localhost ~]# docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
docker.io/busybox latest 018c9d7b792b 4 weeks ago 1.22 MB
docker.io/nginx 1.14-alpine 8a2fb25a19f5 16 months ago 16 MB
查看本地已下载docker镜像列表(完整信息)
[root@localhost ~]# docker image ls --no-trunc
REPOSITORY TAG IMAGE ID CREATED SIZE
docker.io/busybox latest sha256:018c9d7b792b4be80095d957533667279843acf9a46c973067c8d1dff31ea8b4 4 weeks ago 1.22 MB
docker.io/nginx 1.14-alpine sha256:8a2fb25a19f5dc1528b7a3fabe8b3145ff57fe10e4f1edac6c718a3cf4aa4b73 16 months ago 16 MB
查看已经存在的容器列表
下面的两个命令都可以查看
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@localhost ~]# docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
查看本地有多少个网络
[root@localhost ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
570a765cb6d7 bridge bridge local
a2ce16500b13 host host local
850a070c90de none null local
Docker的run命令的i与t参数
[root@localhost ~]# docker run --help
Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Run a command in a new container
Options:
--add-host list Add a custom host-to-IP mapping (host:ip) (default [])
-a, --attach list Attach to STDIN, STDOUT or STDERR (default [])
--blkio-weight uint16 Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
--blkio-weight-device weighted-device Block IO weight (relative device weight) (default [])
--cap-add list Add Linux capabilities (default [])
--cap-drop list Drop Linux capabilities (default [])
--cgroup-parent string Optional parent cgroup for the container
--cidfile string Write the container ID to the file
--cpu-count int CPU count (Windows only)
--cpu-percent int CPU percent (Windows only)
--cpu-period int Limit CPU CFS (Completely Fair Scheduler) period
--cpu-quota int Limit CPU CFS (Completely Fair Scheduler) quota
--cpu-rt-period int Limit CPU real-time period in microseconds
--cpu-rt-runtime int Limit CPU real-time runtime in microseconds
-c, --cpu-shares int CPU shares (relative weight)
--cpus decimal Number of CPUs (default 0.000)
--cpuset-cpus string CPUs in which to allow execution (0-3, 0,1)
--cpuset-mems string MEMs in which to allow execution (0-3, 0,1)
--credentialspec string Credential spec for managed service account (Windows only)
-d, --detach Run container in background and print container ID
--detach-keys string Override the key sequence for detaching a container
--device list Add a host device to the container (default [])
--device-read-bps throttled-device Limit read rate (bytes per second) from a device (default [])
--device-read-iops throttled-device Limit read rate (IO per second) from a device (default [])
--device-write-bps throttled-device Limit write rate (bytes per second) to a device (default [])
--device-write-iops throttled-device Limit write rate (IO per second) to a device (default [])
--disable-content-trust Skip image verification (default true)
--dns list Set custom DNS servers (default [])
--dns-option list Set DNS options (default [])
--dns-search list Set custom DNS search domains (default [])
--entrypoint string Overwrite the default ENTRYPOINT of the image
-e, --env list Set environment variables (default [])
--env-file list Read in a file of environment variables (default [])
--expose list Expose a port or a range of ports (default [])
--group-add list Add additional groups to join (default [])
--health-cmd string Command to run to check health
--health-interval duration Time between running the check (ns|us|ms|s|m|h) (default 0s)
--health-retries int Consecutive failures needed to report unhealthy
--health-timeout duration Maximum time to allow one check to run (ns|us|ms|s|m|h) (default 0s)
--help Print usage
-h, --hostname string Container host name
--init Run an init inside the container that forwards signals and reaps processes
--init-path string Path to the docker-init binary
-i, --interactive Keep STDIN open even if not attached
--io-maxbandwidth string Maximum IO bandwidth limit for the system drive (Windows only)
--io-maxiops uint Maximum IOps limit for the system drive (Windows only)
--ip string Container IPv4 address (e.g. 172.30.100.104)
--ip6 string Container IPv6 address (e.g. 2001:db8::33)
--ipc string IPC namespace to use
--isolation string Container isolation technology
--kernel-memory string Kernel memory limit
-l, --label list Set meta data on a container (default [])
--label-file list Read in a line delimited file of labels (default [])
--link list Add link to another container (default [])
--link-local-ip list Container IPv4/IPv6 link-local addresses (default [])
--log-driver string Logging driver for the container
--log-opt list Log driver options (default [])
--mac-address string Container MAC address (e.g. 92:d0:c6:0a:29:33)
-m, --memory string Memory limit
--memory-reservation string Memory soft limit
--memory-swap string Swap limit equal to memory plus swap: '-1' to enable unlimited swap
--memory-swappiness int Tune container memory swappiness (0 to 100) (default -1)
--name string Assign a name to the container
--network string Connect a container to a network (default "default")
--network-alias list Add network-scoped alias for the container (default [])
--no-healthcheck Disable any container-specified HEALTHCHECK
--oom-kill-disable Disable OOM Killer
--oom-score-adj int Tune host's OOM preferences (-1000 to 1000)
--pid string PID namespace to use
--pids-limit int Tune container pids limit (set -1 for unlimited)
--privileged Give extended privileges to this container
-p, --publish list Publish a container's port(s) to the host (default [])
-P, --publish-all Publish all exposed ports to random ports
--read-only Mount the container's root filesystem as read only
--restart string Restart policy to apply when a container exits (default "no")
--rm Automatically remove the container when it exits
--runtime string Runtime to use for this container
--security-opt list Security Options (default [])
--shm-size string Size of /dev/shm, default value is 64MB
--sig-proxy Proxy received signals to the process (default true)
--stop-signal string Signal to stop a container, SIGTERM by default (default "SIGTERM")
--stop-timeout int Timeout (in seconds) to stop a container
--storage-opt list Storage driver options for the container (default [])
--sysctl map Sysctl options (default map[])
--tmpfs list Mount a tmpfs directory (default [])
-t, --tty Allocate a pseudo-TTY
--ulimit ulimit Ulimit options (default [])
-u, --user string Username or UID (format: <name|uid>[:<group|gid>])
--userns string User namespace to use
--uts string UTS namespace to use
-v, --volume list Bind mount a volume (default [])
--volume-driver string Optional volume driver for the container
--volumes-from list Mount volumes from the specified container(s) (default [])
-w, --workdir string Working directory inside the container
那么i与t合并的意思就是说即便容器没有主动连接也要打开一个终端,那么结合run命令言下之意就是可以直接创建并同时运行一个容器。
创建并运行一个容器
这里-name为你创建的容器命名下,另外就是要传入一个本地镜像名,即你用什么镜像来创建这个容器,镜像名后面跟一个该镜像的版本号,即你用该镜像的什么版本来创建
[root@localhost ~]# docker run --name bl -it busybox:latest
/usr/bin/docker-current: Error response from daemon: Conflict. The container name "/bl" is already in use by container 10a504e419a2da1206ef9bec1339274a34cef3f13788bf1ad4a94f61c763b81b. You have to remove (or rename) that container to be able to reuse that name..
我们可以看到该命令并没有预期的运行成功,这可能是软件版本过低原因,执行yum update之后可以看到命令就可以成功运行了
[root@localhost ~]# docker run --name bl5 -it busybox:latest
/ # ls
bin dev etc home proc root run sys tmp usr var
/ # ps
PID USER TIME COMMAND
1 root 0:00 sh
7 root 0:00 ps
/ # httpd -h
httpd: option requires an argument -- h
BusyBox v1.32.0 (2020-07-27 19:18:59 UTC) multi-call binary.
Usage: httpd [-ifv[v]] [-c CONFFILE] [-p [IP:]PORT] [-u USER[:GRP]] [-r REALM] [-h HOME]
or httpd -d/-e/-m STRING
Listen for incoming HTTP requests
-i Inetd mode
-f Don't daemonize
-v[v] Verbose
-p [IP:]PORT Bind to IP:PORT (default *:80)
-u USER[:GRP] Set uid/gid after binding to port
-r REALM Authentication Realm for Basic Authentication
-h HOME Home directory (default .)
-c FILE Configuration file (default {/etc,HOME}/httpd.conf)
-m STRING MD5 crypt STRING
-e STRING HTML encode STRING
-d STRING URL decode STRING
/ #
这个busybox可以虚拟出一个新的环境在这个环境下勉强算是又一个小型linux吧,模拟了许多linux的命令,像是上面的ps、ls还有模拟的微型httpd。。。
退出该容器用exit命令即可
查看某个容器的信息(这里主要是为了查看该容器的ip地址)
这里需要注意尽量另外开一个终端查看,不然你需要退出当前(上面那个容器)正在打开的容器
[root@localhost ~]# docker inspect bl6
[
{
"Id": "36374b410be354788e0be6d8a83ac607321c94bc83cc82440e03b317ad555b6e",
"Created": "2020-08-29T14:15:01.006793883Z",
"Path": "sh",
"Args": [],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 28700,
"ExitCode": 0,
"Error": "",
"StartedAt": "2020-08-29T14:15:01.138257727Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:018c9d7b792b4be80095d957533667279843acf9a46c973067c8d1dff31ea8b4",
"ResolvConfPath": "/var/lib/docker/containers/36374b410be354788e0be6d8a83ac607321c94bc83cc82440e03b317ad555b6e/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/36374b410be354788e0be6d8a83ac607321c94bc83cc82440e03b317ad555b6e/hostname",
"HostsPath": "/var/lib/docker/containers/36374b410be354788e0be6d8a83ac607321c94bc83cc82440e03b317ad555b6e/hosts",
"LogPath": "",
"Name": "/bl6",
"RestartCount": 0,
"Driver": "overlay2",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig": {
"Binds": null,
"ContainerIDFile": "",
"LogConfig": {
"Type": "journald",
"Config": {}
},
"NetworkMode": "default",
"PortBindings": {},
"RestartPolicy": {
"Name": "no",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": null,
"CapAdd": null,
"CapDrop": null,
"Dns": [],
"DnsOptions": [],
"DnsSearch": [],
"ExtraHosts": null,
"GroupAdd": null,
"IpcMode": "",
"Cgroup": "",
"Links": null,
"OomScoreAdj": 0,
"PidMode": "",
"Privileged": false,
"PublishAllPorts": false,
"ReadonlyRootfs": false,
"SecurityOpt": null,
"UTSMode": "",
"UsernsMode": "",
"ShmSize": 67108864,
"Runtime": "docker-runc",
"ConsoleSize": [
0,
0
],
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": null,
"BlkioDeviceReadBps": null,
"BlkioDeviceWriteBps": null,
"BlkioDeviceReadIOps": null,
"BlkioDeviceWriteIOps": null,
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": [],
"DiskQuota": 0,
"KernelMemory": 0,
"MemoryReservation": 0,
"MemorySwap": 0,
"MemorySwappiness": -1,
"OomKillDisable": false,
"PidsLimit": 0,
"Ulimits": null,
"CpuCount": 0,
"CpuPercent": 0,
"IOMaximumIOps": 0,
"IOMaximumBandwidth": 0
},
"GraphDriver": {
"Name": "overlay2",
"Data": {
"LowerDir": "/var/lib/docker/overlay2/7dd431d7c24e9cea1e939de58c2efbf530e51f7294b5f3bc639b8a79271e9086-init/diff:/var/lib/docker/overlay2/c85fc5ddc2b05c93c6b2682475a635ef62a7d615bafe9b740e81b969d6e6167d/diff",
"MergedDir": "/var/lib/docker/overlay2/7dd431d7c24e9cea1e939de58c2efbf530e51f7294b5f3bc639b8a79271e9086/merged",
"UpperDir": "/var/lib/docker/overlay2/7dd431d7c24e9cea1e939de58c2efbf530e51f7294b5f3bc639b8a79271e9086/diff",
"WorkDir": "/var/lib/docker/overlay2/7dd431d7c24e9cea1e939de58c2efbf530e51f7294b5f3bc639b8a79271e9086/work"
}
},
"Mounts": [],
"Config": {
"Hostname": "36374b410be3",
"Domainname": "",
"User": "",
"AttachStdin": true,
"AttachStdout": true,
"AttachStderr": true,
"Tty": true,
"OpenStdin": true,
"StdinOnce": true,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"sh"
],
"ArgsEscaped": true,
"Image": "busybox:latest",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {}
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "8bfea85dc6d5bb68642e1aaba1db88898217eb4dfed375f1f03f201b778bdd35",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/8bfea85dc6d5",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "ced7920f1f3ca1be38b99d987a501ff3ed724003ee2823203b95a82a585b7e03",
"Gateway": "172.17.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"MacAddress": "02:42:ac:11:00:02",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "570a765cb6d727b196afa8003ed41c3fddf648da8136f66d8b6566b300b0bd60",
"EndpointID": "ced7920f1f3ca1be38b99d987a501ff3ed724003ee2823203b95a82a585b7e03",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02"
}
}
}
}
]
微型httpd
我们既然知道了ip地址,那么我们回到刚才的容器里面建立一个httpd
/ # mkdir /data/html -p
/ # vi /data/html/index.html
/ # httpd -f -h /data/html/
然后我们另外一个会话就可以访问这个httpd了
[root@localhost ~]# curl 172.17.0.2
this is index
退出容器并没有删除容器
只是被停止了
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
36374b410be3 busybox:latest "sh" 8 minutes ago Exited (130) 25 seconds ago bl6
05f9881a6708 busybox:latest "sh" 15 minutes ago Exited (130) 10 minutes ago bl5
b3e2e29e598b busybox:latest "sh" 19 minutes ago Exited (127) 18 minutes ago bl4
58a64a5fd709 busybox:latest "sh" 34 minutes ago Created bl3
5c4f03f15e56 busybox:latest "sh" 38 minutes ago Created bl2
10a504e419a2 busybox:latest "sh" 40 minutes ago Created bl
查看所有容器
其实和上面的命令是同理
[root@localhost ~]# docker container ls -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
36374b410be3 busybox:latest "sh" 10 minutes ago Exited (130) 2 minutes ago bl6
05f9881a6708 busybox:latest "sh" 17 minutes ago Exited (130) 12 minutes ago bl5
b3e2e29e598b busybox:latest "sh" 21 minutes ago Exited (127) 20 minutes ago bl4
58a64a5fd709 busybox:latest "sh" 36 minutes ago Created bl3
5c4f03f15e56 busybox:latest "sh" 40 minutes ago Created bl2
10a504e419a2 busybox:latest "sh" 42 minutes ago Created bl
关于docker的i与a参数
[root@localhost ~]# docker start --help
Usage: docker start [OPTIONS] CONTAINER [CONTAINER...]
Start one or more stopped containers
Options:
-a, --attach Attach STDOUT/STDERR and forward signals
--detach-keys string Override the key sequence for detaching a container
--help Print usage
-i, --interactive Attach container's STDIN
启动一个容器
了解了上面docker的start的i与a参数,那么启动一个容器
[root@localhost ~]# docker start -i -a bl
/ #
Docker ps
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
10a504e419a2 busybox:latest "sh" 48 minutes ago Up About a minute bl
其实这里我主要关注status字段
强制终止某个docker容器
[root@localhost ~]# docker kill bl
Bl
删除某个docker容器
[root@localhost ~]# docker rm bl
Bl
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
36374b410be3 busybox:latest "sh" 19 minutes ago Exited (130) 11 minutes ago bl6
05f9881a6708 busybox:latest "sh" 25 minutes ago Exited (130) 21 minutes ago bl5
b3e2e29e598b busybox:latest "sh" 29 minutes ago Exited (127) 29 minutes ago bl4
58a64a5fd709 busybox:latest "sh" 45 minutes ago Created bl3
5c4f03f15e56 busybox:latest "sh" 49 minutes ago Created bl2
创建容器时临时下载镜像
我们前面了解到容器创建必须要指定一个本地已下载的容器镜像,其实我们也可以直接指定一个本地没有的镜像,它会试图在网络中下载,只要网络中有,只要你的节点中有
[root@localhost ~]# docker run --name web1 -d nginx:1.14-alpine
9f1ed90b19a9731e3a35707911bc1f52a68c813c7a6bae0cc5b30f993d8ae54a
这里为什么会这样呢?是因为-d参数的影响,-d让程序运行在后台,马哥忠告这里最好别让程序运行在后台
同样的这里我们另外一个会话得到新的容器的ip地址,虽然我们刚才让程序运行在后台了,但是容器照样创建成功并且运行成功,然后我们新的会话试图访问该服务
"Aliases": null,
"NetworkID": "570a765cb6d727b196afa8003ed41c3fddf648da8136f66d8b6566b300b0bd60",
"EndpointID": "e5a88b6919ed9a7e3948f901965c89eebb535b2752730d78c8bbbbfec16233d9",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02"
}
}
}
}
]
[root@localhost ~]# curl 172.17.0.2
<!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>
很明显一个nginx就这样实现了。
其实只要能搜到这个镜像就能直接创建这个镜像
[root@localhost ~]# docker run --name kvstorl -d redis:4-alpine
Unable to find image 'redis:4-alpine' locally
Trying to pull repository docker.io/library/redis ...
4-alpine: Pulling from docker.io/library/redis
cbdbe7a5bc2a: Pull complete
dc0373118a0d: Pull complete
cfd369fe6256: Pull complete
152ffd6a3b24: Pull complete
7c01860f13a3: Pull complete
aa6ecacd3bee: Pull complete
Digest: sha256:aaf7c123077a5e45ab2328b5ef7e201b5720616efac498d55e65a7afbb96ae20
Status: Downloaded newer image for docker.io/redis:4-alpine
6e2f3d9d2545363014781c5914a0441d83af22045809992521a1dac9301cf50e
向容器内部发送指令
[root@localhost ~]# docker exec -it kvstorl /bin/sh
/data # ps
PID USER TIME COMMAND
1 redis 0:00 redis-server
12 root 0:00 /bin/sh
17 root 0:00 ps
/data # netstat -tnl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:6379 0.0.0.0:* LISTEN
tcp 0 0 :::6379 :::* LISTEN
/data # redis-cli
127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379> select 1
OK
正是由于sh命令即bash所以这个容器也被成功打开了,然后可以看到里面各种命令都是很轻松就能玩耍的。
注意:这里select的意思是:
选择Redis逻辑数据库,index从0开始的整数。新连接总是使用数据库0。
查看某个容器的日志
[root@localhost ~]# docker logs web1
172.17.0.1 - - [29/Aug/2020:14:39:48 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
关键字词:docker,nginx,httpd,busybox
上一篇:workman框架开发网络应用
下一篇:03-Docker镜像管理基础