Docker入门(二)基本操作

(一)、容器的使用
1、docker客户端命令。输入docker查看docker用法的语法和相关的命令。

[[email protected] ~]# docker
Usage:  docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
Options:
      --config string      Location of client config files (default "/root/.docker")
  -D, --debug              Enable debug mode
  -H, --host list          Daemon socket(s) to connect to
  -l, --log-level string   Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
      --tls                Use TLS; implied by --tlsverify
      --tlscacert string   Trust certs signed only by this CA (default "/root/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/root/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/root/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit
Management Commands:
  config      Manage Docker configs
  container   Manage containers
  image       Manage images
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  secret      Manage Docker secrets
  service     Manage services
  stack       Manage Docker stacks
  swarm       Manage Swarm
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  build       Build an image from a Dockerfile
  commit      Create a new image from a container‘s changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container‘s filesystem
  events      Get real time events from the server
  exec        Run a command in a running container
  export      Export a container‘s filesystem as a tar archive
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a Docker registry
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  ps          List containers
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  search      Search the Docker Hub for images
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  version     Show the Docker version information
  wait        Block until one or more containers stop, then print their exit codes

Run ‘docker COMMAND --help‘ for more information on a command.

2、启动docker。

[[email protected] ~]# docker run ubuntu /bin/echo "hello docker"    ###基本运行,打印后退出
hello docker
[[email protected] ~]# docker run -i -t -h centosv2 centos /bin/bash   ###交互式创建容器后进入容器并命名为centosv2
[[email protected] ~]# docker run -d ubuntu /bin/sh -c "while true; do echo hello world; sleep 1; done" ###后台运行
5011198d1704af7eac453f80e58fa4950e6455c4454b28fa8a877a5f69cdb8fc

3、docker端口的映射

[[email protected] ~]#docker run -t -P httpd                             ---指定容器绑定的网络地址,比如绑定 127.0.0.1。
[[email protected] ~]#docker run -t -p 8888:80  httpd                    ---指定容器80端口通过主机端口地址8888来进行访问
[[email protected] ~]#docker run -t -p 172.20.66.150:8888:80  httpd      ---指定容器绑定的网络地址默认tcp端口
[[email protected] ~]#docker run -t -p 172.20.66.150:8888:80/udp  httpd  ---指定udp端口
-P :是容器内部端口随机映射到主机的高端口。
-p : 是容器内部端口绑定到指定的主机端口。
8888:80(主机端口:容器的端口)

4、查看docker容器。

[[email protected] ~]# docker ps --help
Usage:  docker ps [OPTIONS]
List containers
Options:
  -a, --all             Show all containers (default shows just running)
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print containers using a Go template
  -n, --last int        Show n last created containers (includes all states) (default -1)
  -l, --latest          Show the latest created container (includes all states)
      --no-trunc        Don‘t truncate output
  -q, --quiet           Only display numeric IDs
  -s, --size            Display total file sizes
[[email protected] ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
5011198d1704        ubuntu              "/bin/sh -c ‘while t…"   6 minutes ago       Up 6 minutes                            laughing_mirzakhani
5f55b9949e7b        centos              "/bin/bash"              18 minutes ago      Up 18 minutes                           centosv3

5、停止docker容器。docker stop CONTAINER或ID

[[email protected] ~]# docker stop --help
Usage:  docker stop [OPTIONS] CONTAINER [CONTAINER...]
Stop one or more running containers
Options:
  -t, --time int   Seconds to wait for stop before killing it (default 10)
[[email protected] ~]# docker stop centosv3
centosv3
[[email protected] ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
5011198d1704        ubuntu              "/bin/sh -c ‘while t…"   8 minutes ago       Up 8 minutes                            laughing_mirzakhani

6、启动docker.

[[email protected] ~]# docker start nginxv2
nginxv2

7、删除docker容器.删除容器时,容器必须是停止状态,否则会报如下错误

[[email protected] ~]# docker rm 2c1aed05442e
2c1aed05442e
[[email protected] ~]# docker rm --help
Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]
Remove one or more containers
Options:
  -f, --force     Force the removal of a running container (uses SIGKILL)
  -l, --link      Remove the specified link
  -v, --volumes   Remove the volumes associated with the container

8、查看docker日志

[[email protected] ~]# docker logs --help
Usage:  docker logs [OPTIONS] CONTAINER
Fetch the logs of a container
Options:
      --details        Show extra details provided to logs
  -f, --follow         Follow log output
      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
      --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps
      --until string   Show logs before a timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
[[email protected] ~]# docker logs -f 5011198d1704
hello world

9、检查docker应用程序的进程
[[email protected] ~]# docker top nginxv2
UID PID PPID C STIME TTY TIME CMD
root 22446 22428 0 17:56 ? 00:00:00 nginx: master process nginx -g daemon off;
101 22490 22446 0 17:56 ? 00:00:00 nginx: worker process

10、查看docker底层信息,它会返回一个 JSON 文件记录着 Docker 容器的配置和状态信息。

[[email protected] ~]# docker inspect nginxv2
[
    {
        "Id": "51fa7e93382191d3d52dfd8231baa47438f30472a9ddb432cac95f2cab09c377",
        "Created": "2018-10-23T07:35:16.522767558Z",
        "Path": "nginx",
        "Args": [
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 22446,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2018-10-24T09:56:50.60288752Z",
            "FinishedAt": "2018-10-23T07:35:20.710607429Z"
        },
        "Image": "sha256:dbfc48660aeb7ef0ebd74b4a7e0822520aba5416556ee43acb9a6350372e516f",
        "ResolvConfPath": "/var/lib/docker/containers/51fa7e93382191d3d52dfd8231baa47438f30472a9ddb432cac95f2cab09c377/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/51fa7e93382191d3d52dfd8231baa47438f30472a9ddb432cac95f2cab09c377/hostname",
        "HostsPath": "/var/lib/docker/containers/51fa7e93382191d3d52dfd8231baa47438f30472a9ddb432cac95f2cab09c377/hosts",
        "LogPath": "/var/lib/docker/containers/51fa7e93382191d3d52dfd8231baa47438f30472a9ddb432cac95f2cab09c377/51fa7e93382191d3d52dfd8231baa47438f30472a9ddb432cac95f2cab09c377-json.log",
        "Name": "/nginxv2",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "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": "shareable",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DiskQuota": 0,
            "KernelMemory": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": 0,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/asound",
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/e5db810fb9cc01e72997ab28548f8c6afdf288ad68b67526b8a08db21f11cc4d-init/diff:/var/lib/docker/overlay2/9aa976c9f96e990dc230b219d4c004c40b83c018a2f4f5c7e8aeeddce78d56f9/diff:/var/lib/docker/overlay2/aeb079bd298ea309e97c1ca135f5cedb5832a4222477479f00c04e20eac5bda0/diff:/var/lib/docker/overlay2/a69b7899845f36bdc82307abbec8b0150892f4f30ba2f59fedd076b5ba84cd46/diff",
                "MergedDir": "/var/lib/docker/overlay2/e5db810fb9cc01e72997ab28548f8c6afdf288ad68b67526b8a08db21f11cc4d/merged",
                "UpperDir": "/var/lib/docker/overlay2/e5db810fb9cc01e72997ab28548f8c6afdf288ad68b67526b8a08db21f11cc4d/diff",
                "WorkDir": "/var/lib/docker/overlay2/e5db810fb9cc01e72997ab28548f8c6afdf288ad68b67526b8a08db21f11cc4d/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "51fa7e933821",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.15.5-1~stretch",
                "NJS_VERSION=1.15.5.0.2.4-1~stretch"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "ArgsEscaped": true,
            "Image": "nginx",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <[email protected]>"
            },
            "StopSignal": "SIGTERM"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "8fb89b8da81ef113f293fff99eba54a8dddc8027a47ec5e3094b0c50023cb9c7",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": null
            },
            "SandboxKey": "/var/run/docker/netns/8fb89b8da81e",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "c6f8a321d3fb49fa82d27e1a430639fd1617df75b86641e8deb720c0ce57989b",
            "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": "56fd3fad5cf9211915ead97854e1bf8ef6e061ea1409264cb92c78296cc92314",
                    "EndpointID": "c6f8a321d3fb49fa82d27e1a430639fd1617df75b86641e8deb720c0ce57989b",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]

(11)连接到正在运行中的容器。docker exec|docker attach |nsenter

attach命令:docker attach name | id
docker exec :在运行的容器中执行命令(运行中容器启动新进程)
[[email protected] ~]# cat /home/docker_pid.sh
#!/bin/bash
docker_in(){
    NAME_ID=$1
    PID=$(docker inspect -f "{{ .State.Pid }}" $NAME_ID)
    nsenter -t $PID -m -u -i -n -p
}
docker_in $1
[[email protected] ~]# docker attach nginxv2
[[email protected] ~]# docker exec -i -t nginxv2 /bin/bash
[email protected]:/#
[[email protected] ~]# sh /home/docker_pid.sh nginxv2
[email protected]:/# 

(二)docker镜像的使用

1、docker镜像的使用

[[email protected] ~]# docker images --help
Usage:  docker images [OPTIONS] [REPOSITORY[:TAG]]
List images
Options:
  -a, --all             Show all images (default hides intermediate images)
      --digests         Show digests
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print images using a Go template
      --no-trunc        Don‘t truncate output
  -q, --quiet           Only show numeric IDs
[[email protected] ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              ea4c82dcd15a        6 days ago          85.8MB
grafana/grafana     latest              7038dbc9a50c        8 days ago          223MB
nginx               latest              dbfc48660aeb        8 days ago          109MB
centos              latest              75835a67d134        2 weeks ago         200MB

REPOSITORY:表示镜像的仓库源
TAG:镜像的标签
IMAGE ID:镜像ID
CREATED:镜像创建时间
SIZE:镜像大小 

2、搜索镜像

[[email protected] ~]# docker search zabbix
NAME                                       DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
zabbix/zabbix-server-mysql                 Zabbix Server with MySQL database support       136                                     [OK]
zabbix/zabbix-agent                        Zabbix agent with TLS encryption support        83                                      [OK]
monitoringartist/zabbix-3.0-xxl            Please use our better compatible Zabbix imag…   75                                      [OK]
zabbix/zabbix-web-nginx-mysql              Zabbix frontend based on Nginx web-server wi…   74                                      [OK]
berngp/docker-zabbix                       Runs Zabbix Server and Zabbix Web UI on a Ce…   72                                      [OK]
monitoringartist/zabbix-xxl                Zabbix 3.x - server, web, proxy, java gatewa…   67                                      [OK]
zabbix/zabbix-server-pgsql                 Zabbix server with PostgreSQL database suppo…   33                                      [OK]
zabbix/zabbix-web-nginx-pgsql              Zabbix frontend based on Nginx with PostgreS…   20                                      [OK]
zabbix/zabbix-appliance                    Zabbix appliance with MySQL database support…   18                                      [OK]
zabbix/zabbix-web-apache-mysql             Zabbix frontend based on Apache web-server w…   17                                      [OK]
zabbix/zabbix-proxy-mysql                  Zabbix proxy with MySQL database support        16                                      [OK]
zabbix/zabbix-proxy-sqlite3                Zabbix proxy with SQLite3 database support      15                                      [OK]
zabbix/zabbix-java-gateway                 Zabbix Java Gateway                             14                                      [OK]
bhuisgen/docker-zabbix-coreos              Zabbix agent for CoreOS server                  14                                      [OK]
monitoringartist/zabbix-db-mariadb         Docker image of MariaDB optimized for Zabbix    11                                      [OK]
million12/zabbix-agent                     Zabbix Agent - running in foreground.           7                                       [OK]
zabbix/zabbix-snmptraps                    Receiving SNMP traps to Zabbix server or Zab…   7                                       [OK]
zabbix/zabbix-web-apache-pgsql             Zabbix frontend based on Apache web-server w…   3                                       [OK]
digiapulssi/docker-zabbix-agent            Dockerized Zabbix agent for host and contain…   2                                       [OK]
openshifttools/oso-centos7-zabbix-server   Zabbix server container using external SQL d…   2
blackcobra1973/zabbix-db-postgresql        PostgreSQL on CentOS 7.x with Zabbix 3.0 dat…   2                                       [OK]
monitoringartist/zabbix-2.4                Dockerized Zabbix 2.4 - server, web UI - dep…   1                                       [OK]
qk4l/zabbix-cachet                         Python script for Zabbix to Cachet integrati…   0                                       [OK]
signnow/zabbix-proxy-mysql                 Zabbix Proxy (MySQL version) with Python 3.5…   0
openshifttools/oso-centos7-zabbix-web      Zabbix web container to handle web view into…   0
NAME:镜像仓库源的名称
DESCRIPTION:镜像的描述
OFFICIAL:是否docker官方发布

3、获取镜像

[[email protected] ~]# docker pull zabbix/zabbix-server-mysql
Using default tag: latest
latest: Pulling from zabbix/zabbix-server-mysql
d6a5679aa3cf: Pull complete
b5f72c9bbb93: Pull complete
e901ef2029a4: Pull complete
9ba83f201d25: Pull complete
Digest: sha256:f385294e950ec855338df5e6bec41ed708cc6cbd00e1ba266d1c425d0ed9fd1e
Status: Downloaded newer image for zabbix/zabbix-server-mysql:latest

4、查看镜像

[[email protected] ~]# docker images
REPOSITORY                   TAG                 IMAGE ID            CREATED             SIZE
ubuntu                       latest              ea4c82dcd15a        6 days ago          85.8MB
grafana/grafana              latest              7038dbc9a50c        8 days ago          223MB
nginx                        latest              dbfc48660aeb        8 days ago          109MB
centos                       latest              75835a67d134        2 weeks ago         200MB
zabbix/zabbix-server-mysql   latest              efffb1148f04        2 weeks ago         62.6MB

5、更新镜像

[[email protected] ~]# docker run -t -i ubuntu /bin/bash
[email protected]:/# apt-get upgrade
Reading package lists... Done
Get:16 http://archive.ubuntu.com/ubuntu bionic-backports/universe amd64 Packages [2975 B]
Fetched 15.0 MB in 6s (2714 kB/s)
Reading package lists... Done
[email protected]:/# apt-get install vim -y
Reading package lists... Done
update-alternatives: warning: skip creation of /usr/share/man/man1/editor.1.gz because associated file /usr/share/man/man1/vim.1.gz (of link group editor) doesn‘t exist
Processing triggers for libc-bin (2.27-3ubuntu1) ...
[email protected]:/# hostname
a9247c958d01
[email protected]:/# exit;
exit
[[email protected] ~]# docker commit -m="apt-get update" -a=lqb a9247c958d01  ubuntu/lqbv2
sha256:61e3695d2d9fd6c5800fba1119335c5f146bfa859a35591d29c725e6fdaafe07
[[email protected] ~]# docker images
REPOSITORY                   TAG                 IMAGE ID            CREATED             SIZE
ubuntu/lqbv2                 latest              61e3695d2d9f        4 minutes ago       169MB

各个参数说明:
-m:提交的描述信息
-a:指定镜像作者
a9247c958d01:容器ID
runoob/ubuntu:v2:指定要创建的目标镜像名

创建更新镜像的相关说明:
首先创建用ubuntu镜像创建容器。
运行的容器内使用 apt-get update 命令进行更新。
在完成操作之后,输入 exit命令来退出这个容器。
此时ID为a9247c958d01的容器,是按我们的需求更改的容器。我们可以通过命令 docker commit来提交容器副本

6、构建镜像。通过docker build从零开始来创建一个新的镜像。为此,我们需要创建一个 Dockerfile 文件,其中包含一组指令来告诉 Docker 如何构建我们的镜像。

[[email protected] ~]# mkdir /opt/dockerfile
[[email protected] dockerfile]# mkdir centos
[[email protected] dockerfile]# cd centos/
[[email protected] centos]# vim Dockfile
[[email protected] centos]# vim Dockerfile
FROM centos
MAINTAINER lqb
RUN  yum install vim -y
RUN yum install tree  -y
RUN    /bin/echo ‘root:123456‘ |chpasswd
RUN     useradd lqb
RUN     /bin/echo ‘lqb:123456‘ |chpasswd
RUN     /bin/echo -e "LANG=\"en_US.UTF-8\"" >/etc/default/local
EXPOSE  22
EXPOSE  80
CMD     /usr/sbin/sshd -D
[[email protected] centos]# docker build -t centos/lqb:lqbv2  .
Sending build context to Docker daemon  2.048kB
Step 1/11 : FROM centos
 ---> 75835a67d134
Step 2/11 : MAINTAINER lqb
 ---> Using cache
 ---> 386b6f69c473
Step 3/11 : RUN  yum install vim -y
 ---> Using cache
 ---> 745792f01962
Step 4/11 : RUN yum install tree  -y
 ---> Using cache
 ---> 2bae22865096
Step 5/11 : RUN    /bin/echo ‘root:123456‘ |chpasswd
 ---> Using cache
 ---> f554337a5fee
Step 6/11 : RUN     useradd lqb
 ---> Using cache
 ---> 7f08790bd10d
Step 7/11 : RUN     /bin/echo ‘lqb:123456‘ |chpasswd
 ---> Using cache
 ---> 40a26046eb5a
Step 8/11 : RUN     /bin/echo -e "LANG=\"en_US.UTF-8\"" >/etc/default/local
 ---> Using cache
 ---> af9ca664315f
Step 9/11 : EXPOSE  22
 ---> Using cache
 ---> e24bed6f62fe
Step 10/11 : EXPOSE  80
 ---> Using cache
 ---> 938e49766589
Step 11/11 : CMD     /usr/sbin/sshd -D
 ---> Using cache
 ---> 466ccf2de68e
Successfully built 466ccf2de68e
Successfully tagged centos/lqb:lqbv2
[[email protected] centos]# docker images
REPOSITORY                   TAG                 IMAGE ID            CREATED             SIZE
centos/lqb                   lqbv2               466ccf2de68e        8 minutes ago       455MB
<none>                       <none>              9d09c724aa58        2 hours ago         200MB

每一个指令都会在镜像上创建一个新的层,每一个指令的前缀都必须是大写的。
第一条FROM,指定使用哪个镜像源
RUN 指令告诉docker 在镜像内执行命令,安装了什么。
ADD添加相应的文件,会自动解压
WORKDIR设置当前的工作目录
VOLUME设置卷,挂载主机目录
EXPOSE指定对外的端口
CMD指定容器启动后要干的事情

参数说明:
-t :指定要创建的目标镜像名
. :Dockerfile 文件所在目录,可以指定Dockerfile 的绝对路径

7、设置镜像标签

[[email protected] centos]# docker tag 9d09c724aa58  centoslqb1:lqbcentosv1
[[email protected] centos]# docker images
REPOSITORY                   TAG                 IMAGE ID            CREATED             SIZE
centos/lqb                   lqbv2               466ccf2de68e        23 minutes ago      455MB
centoslqb1                   lqbcentosv1         9d09c724aa58        3 hours ago         200MB

8、删除镜像。通过docker rmi来进行删除。

[[email protected] centos]# docker rmi 9d09c724aa58
Untagged: centoslqb1:lqbcentosv1
Deleted: sha256:9d09c724aa58ee7bf22e1b3ed7aaa53437c4e57eaa1ed47b66fbde62d3946a75
[[email protected] centos]# docker images
REPOSITORY                   TAG                 IMAGE ID            CREATED             SIZE
centos/lqb                   lqbv2               466ccf2de68e        28 minutes ago      455MB

(三)容器的连接
通过一个端口实现连接一个docker容器

1、网络端口的映射-----随机映射。docker run -P 。-P :是容器内部端口随机映射到主机的高端口。

[[email protected] centos]# docker run -t -i -d -P httpd /bin/bash
273c5df97d67e8bd256deb22b3b325f56a3c7b25cd113509cfffe3346ceaa285
[[email protected] centos]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                   NAMES
273c5df97d67        httpd               "/bin/bash"              4 seconds ago       Up 4 seconds        0.0.0.0:32773->80/tcp   quirky_stonebraker
51fa7e933821        nginx               "nginx -g ‘daemon of…"   2 days ago          Up 21 hours         80/tcp                  nginxv2

2、网络端口的映射-----指定映射 docker run -d -p 。

[[email protected] centos]# docker run -t -p 8888:80 httpd
AH00558: httpd: Could not reliably determine the server‘s fully qualified domain name, using 172.17.0.2. Set the ‘ServerName‘ directive globally to suppress this message
AH00558: httpd: Could not reliably determine the server‘s fully qualified domain name, using 172.17.0.2. Set the ‘ServerName‘ directive globally to suppress this message
[Thu Oct 25 08:02:42.006060 2018] [mpm_event:notice] [pid 1:tid 140406403273920] AH00489: Apache/2.4.37 (Unix) configured -- resuming normal operations
[Thu Oct 25 08:02:42.006225 2018] [core:notice] [pid 1:tid 140406403273920] AH00094: Command line: ‘httpd -D FOREGROUND‘
172.20.18.255 - - [25/Oct/2018:08:02:51 +0000] "GET / HTTP/1.1" 200 45

3、指定ip地址的映射

[[email protected] centos]# docker run -t -p 172.20.66.113:8888:80 httpd
AH00558: httpd: Could not reliably determine the server‘s fully qualified domain name, using 172.17.0.2. Set the ‘ServerName‘ directive globally to suppress this message
AH00558: httpd: Could not reliably determine the server‘s fully qualified domain name, using 172.17.0.2. Set the ‘ServerName‘ directive globally to suppress this message
[Thu Oct 25 08:03:44.093560 2018] [mpm_event:notice] [pid 1:tid 140221092869312] AH00489: Apache/2.4.37 (Unix) configured -- resuming normal operations
[Thu Oct 25 08:03:44.093720 2018] [core:notice] [pid 1:tid 140221092869312] AH00094: Command line: ‘httpd -D FOREGROUND‘

4、指定相关的传输协议的映射

[[email protected] centos]# docker run -t -p 172.20.66.113:8000:80/udp httpd
AH00558: httpd: Could not reliably determine the server‘s fully qualified domain name, using 172.17.0.3. Set the ‘ServerName‘ directive globally to suppress this message
AH00558: httpd: Could not reliably determine the server‘s fully qualified domain name, using 172.17.0.3. Set the ‘ServerName‘ directive globally to suppress this message
[Thu Oct 25 08:05:33.630321 2018] [mpm_event:notice] [pid 1:tid 139959673029824] AH00489: Apache/2.4.37 (Unix) configured -- resuming normal operations
[Thu Oct 25 08:05:33.630494 2018] [core:notice] [pid 1:tid 139959673029824] AH00094: Command line: ‘httpd -D FOREGROUND‘
[[email protected] ~]# docker ps
CONTAINER ID        IMAGE               COMMAND              CREATED             STATUS              PORTS                                NAMES
433ec39bebfe        httpd               "httpd-foreground"   31 seconds ago      Up 31 seconds       80/tcp, 172.20.66.113:8000->80/udp   fervent_edison
27161fa1179a        httpd               "httpd-foreground"   2 minutes ago       Up 2 minutes        172.20.66.113:8888->80/tcp           vigilant_spence

备注:
-p hostPort:containerPort
-p ip:hostPort:containerPort
-p ip::containerPort
-p hostPort:containerPort:udp
-p 81:80 –p 443:443

(四)、数据卷的挂载
1、挂载默认路径的卷

[[email protected] centos]# docker run -d --name nginx-volume -v /data nginx
36195574d6f468d008197c81066893b99e9459079ee6953c768a3dd2f2732b4c
[[email protected] centos]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                        NAMES
36195574d6f4        nginx               "nginx -g ‘daemon of…"   9 seconds ago       Up 8 seconds        80/tcp                       nginx-volume
27161fa1179a        httpd               "httpd-foreground"       11 minutes ago      Up 11 minutes       172.20.66.113:8888->80/tcp   vigilant_spence
[[email protected] centos]# sh /home/docker_pid.sh 36195574d6f4
[email protected]:/# hostname
36195574d6f4
[email protected]:/# df -h
Filesystem               Size  Used Avail Use% Mounted on
overlay                   50G  8.4G   42G  17% /
tmpfs                     64M     0   64M   0% /dev
tmpfs                    1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/mapper/centos-root   50G  8.4G   42G  17% /data
shm                       64M     0   64M   0% /dev/shm
tmpfs                    1.9G     0  1.9G   0% /proc/acpi
tmpfs                    1.9G     0  1.9G   0% /proc/scsi
tmpfs                    1.9G     0  1.9G   0% /sys/firmware
[email protected]:/# touch /data/2.log
[email protected]:/# ls /data/
1.log  2.log  test
[[email protected] data]# docker inspect -f {{.Mounts}} nginx-volume
[{volume b989bef7efdc81fe63c76914f5f2e4621db327a5bf5136fab5b9dd09f994b23c /var/lib/docker/volumes/b989bef7efdc81fe63c76914f5f2e4621db327a
[[email protected] data]# cd /var/lib/docker/volumes/b989bef7efdc81fe63c76914f5f2e4621db327a5bf5136fab5b9dd09f994b23c/_data/
1.log  test/
[[email protected] data]# cd /var/lib/docker/volumes/b989bef7efdc81fe63c76914f5f2e4621db327a5bf5136fab5b9dd09f994b23c/_data/
[[email protected] _data]# ls
[[email protected] _data]# ls
1.log  2.log  test

所有的文件都是挂载到主机var/lib/docker/volumes/b989bef7efdc81fe63c76914f5f2e4621db327a5bf5136fab5b9dd09f994b23c/_data /下

2、指定好相关路径的数据卷

[[email protected] _data]# mkdir /data/volumnes
[[email protected] _data]# docker run -d --name nginx-volumes2 -v /data/volumnes/:/data/ nginx
5a4e5e692732368888f3b9c4ce920b8281ca23b0eaf01f3ba93392d84e63c3ff
[[email protected] _data]# docekr ps
-bash: docekr: command not found
[[email protected] _data]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                        NAMES
5a4e5e692732        nginx               "nginx -g ‘daemon of…"   19 seconds ago      Up 18 seconds       80/tcp                       nginx-volumes2
36195574d6f4        nginx               "nginx -g ‘daemon of…"   15 minutes ago      Up 15 minutes       80/tcp                       nginx-volume
27161fa1179a        httpd               "httpd-foreground"       26 minutes ago      Up 26 minutes       172.20.66.113:8888->80/tcp   vigilant_spence
[[email protected] _data]# sh /home/docker_pid.sh 5a4e5e692732
mesg: ttyname failed: No such file or directory
[email protected]:/# df -h
Filesystem               Size  Used Avail Use% Mounted on
overlay                   50G  8.4G   42G  17% /
tmpfs                     64M     0   64M   0% /dev
tmpfs                    1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/mapper/centos-root   50G  8.4G   42G  17% /data
shm                       64M     0   64M   0% /dev/shm
tmpfs                    1.9G     0  1.9G   0% /proc/acpi
tmpfs                    1.9G     0  1.9G   0% /proc/scsi
tmpfs                    1.9G     0  1.9G   0% /sys/firmware
[email protected]:/# cd /data/
[email protected]:/data# ls
[email protected]:/data# touch lqb.log
## 2、在容器里进行查看
[email protected]:/data# cat yz.txt
11111111
2222222222
[email protected]:/data# ls
lqb.log  yz.txt

## 1、在宿主机上创建文件
[[email protected] centos]# vim /data/volumnes/yz.txt

11111111
2222222222

3、挂载数据卷容器(一个容器可以挂载另一个容器所使用的卷共享存储)

[[email protected] centos]# docker run -it --name volumes3 --volumes-from nginx-volume centos /bin/bash
[[email protected] /]# df -h
Filesystem               Size  Used Avail Use% Mounted on
overlay                   50G  8.4G   42G  17% /
tmpfs                     64M     0   64M   0% /dev
tmpfs                    1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/mapper/centos-root   50G  8.4G   42G  17% /data
shm                       64M     0   64M   0% /dev/shm
tmpfs                    1.9G     0  1.9G   0% /proc/acpi
tmpfs                    1.9G     0  1.9G   0% /proc/scsi
tmpfs                    1.9G     0  1.9G   0% /sys/firmware
[[email protected] /]# cd /data/
[[email protected] data]# ls
1.log  2.log  test
[[email protected] data]# cat 1.log
11112

原文地址:http://blog.51cto.com/liqingbiao/2308924

时间: 2024-10-08 17:53:43

Docker入门(二)基本操作的相关文章

Docker入门二:容器管理

Docker入门二:容器管理 LinuxDocker time: 2019-12-3 容器管理 docker常用命令 注: 命令中的CONTAINER,可以是conainer_id,也可以是container name docker system info # 查看docker系统信息 docker container ls -a 查看当前已经创建的container docker container ls: -a 显示所有容器 -q 仅显示ID -s 显示container的文件大小 快速启动

Docker入门 二

hello world 在命令行任意位置下运行> docker run hello-world结果 这样说明安装成功了.

Docker入门二

容器管理 1.docker create创建一个容器,但容器并没启动,就和我们创建虚拟机一样,创建了虚拟机后没启动 [[email protected] ~]# docker create -it centos6 bash WARNING: IPv4 forwarding is disabled. Networking will not work. 558e31f7b0fb941ca4ee8c1c2b42553b06ac79c0613984b7ad8b9b4ba97f61fd [[email p

【实战】Docker入门实践二:Docker服务基本操作 和 测试Hello World

操作环境 操作系统:CentOS7.2 内存:1GB CPU:2核 Docker服务常用命令 docker服务操作命令如下 service docker start #启动服务 service docker stop  #停止服务 service docker restart #重启服务 service docker status   #查看服务状态 启动Docker服务 docker是一个CS模型,需要先启动服务端,直接执行 sudo service docker start 启动docker

Docker入门教程(二)命令

Docker入门教程(二)命令 [编者的话]DockerOne组织翻译了Flux7的Docker入门教程,本文是系列入门教程的第二篇,介绍了Docker的基本命令以及命令的用法和功能. 在Docker系列教程的第一篇文章中,我们了解了Docker的基础知识,知道了它是如何工作以及如何安装的.在这篇文章中,我们将学习15个Docker命令,并通过实践来学习它是如何工作的. 首先,让我们通过下面的命令来检查Docker的安装是否正确: docker info  如果没有找到这条命令,则表示Docke

【实战】Docker 入门实战一

Docker是什么 Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从Apache2.0协议开源.Docker 可以让开发者打包他们的应用以及依赖包到一个轻量级.可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化.容器是完全使用沙箱机制,相互之间不会有任何接口(类似 iPhone 的 app),更重要的是容器性能开销极低 从这个解释我们不知道大家有没有想到一个优点类似的东西,没错就是 Vagrant :  vagrant打造跨平台可移动的开发环境   ,那么

Docker 入门实践

欢迎大家前往腾讯云技术社区,获取更多腾讯海量技术实践干货哦~ 作者:张戈 导语 本文从新手视角记录了一个实际的Dokcer应用场景从创建.上传直到部署的详细过程,并简单的介绍了腾讯云容器服务的使用方法.通过Docker快速拉起一个定制服务,极大的简化了部署,加快了业务部署节奏,并降低了运维成本. ------ 人生苦短,快用Docker. 一.实践背景 初次接触Docker,按照我的学习习惯,先设计了这样一个场景case:假设有一个小型网站,想使用Nginx反向代理方案,能够在国内外快速搭建多个

微服务SpringCloud+Docker入门到高级实战

第一章 课程介绍和学习路线 1.微服务架构SpringCloud课程介绍简介:课程介绍和课程大纲讲解,讲课风格和重点内容理解技巧2.技术选型和学后水平简介:课程所需基础和技术选型讲解,学完课程可以到达怎样的程度, 第二章 架构演进和分布式系统基础知识 1.传统架构演进到分布式架构简介:讲解单机应用和分布式应用架构演进基础知识 (画图)2.微服务核心基础讲解简介:讲解微服务核心知识 :网关.服务发现注册.配置中心.链路追踪.负载均衡器.熔断3.常见的微服务框架简介:讲解常用的微服务框架4.微服务下

docker入门之简单的容器使用

docker入门之简单的容器使用 首发:arppinging 一.运行容器 1)搜索和下载镜像 在之前我们打过一个比分,容器就像vmware workstation一样,而镜像类似于一个OVA文件,如果我们想让容器变得有意义,那镜像是我们必不可少的一个"货物". 跟OVA文件类似,如果我们基于某一个镜像创建容器,那么在容器里面的任何操作不会被写入原本的镜像,除非对所有的操作进行一次镜像重构,把所有操作的结果导出形成一个新的镜像. 1.1 搜索需要的镜像 格式:docker search

Docker入门学习1 ——概述

摘要:本文为Docker基本介绍.了解Docker的概念与组成,可以在命令的学习中更好地构建起体系,也可以与之前的知识融会贯通. 知识点:Docker用途 组成 原理,Docker容器简介 一.Docker入门介绍 Docker是什么? 简单来说,docker是一种比虚拟机更方便的虚拟化环境.有多方便?举个例子,以前想在Windows环境运行LAMP服务器,需要下载安装VMWare一类的虚拟机管理工具,再安装linux虚拟机,再安装LAMP环境:现在只要在docker中通过定制的镜像创建需要的容