ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

030_Docker常用命令

2022-07-03 15:00:36  阅读:167  来源: 互联网

标签:-- admin 214025 ecs Docker 常用命令 docker root 030


目录

帮助命令

docker version

:::info
显示docker的版本信息
docker version
:::

[root@ecs-214025 admin]# docker version
Client: Docker Engine - Community
 Version:           20.10.17
 API version:       1.41
 Go version:        go1.17.11
 Git commit:        100c701
 Built:             Mon Jun  6 23:05:12 2022
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.17
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.17.11
  Git commit:       a89b842
  Built:            Mon Jun  6 23:03:33 2022
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.6.6
  GitCommit:        10c12954828e7c7c9b6e0ea9b0c02b01407d3ae1
 runc:
  Version:          1.1.2
  GitCommit:        v1.1.2-0-ga916309
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0
[root@ecs-214025 admin]# 

docker info

:::info
显示docker的系统信息,包括镜像和容器的数量
docker info
:::

[root@ecs-214025 admin]# docker info
Client:
 Context:    default
 Debug Mode: false
 Plugins:
  app: Docker App (Docker Inc., v0.9.1-beta3)
  buildx: Docker Buildx (Docker Inc., v0.8.2-docker)
  compose: Docker Compose (Docker Inc., v2.6.0)
  scan: Docker Scan (Docker Inc., v0.17.0)

Server:
 Containers: 1
  Running: 0
  Paused: 0
  Stopped: 1
 Images: 1
 Server Version: 20.10.17
 Storage Driver: overlay2
  Backing Filesystem: extfs
  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: 10c12954828e7c7c9b6e0ea9b0c02b01407d3ae1
 runc version: v1.1.2-0-ga916309
 init version: de40ad0
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 3.10.0-1160.62.1.el7.x86_64
 Operating System: CentOS Linux 7 (Core)
 OSType: linux
 Architecture: x86_64
 CPUs: 1
 Total Memory: 1.794GiB
 Name: ecs-214025
 ID: VN4P:FIOX:SETH:2YJE:3IUF:AXFE:QJ34:555N:EMDQ:VOFJ:JMHP:YS3V
 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
 Live Restore Enabled: false

[root@ecs-214025 admin]# 

docker --help

:::info
帮助命令
docker --help # 所有命令的帮助信息
docker version --help # version命令的帮助信息
:::

[root@ecs-214025 admin]# docker --help

Usage:  docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/root/.docker")
  -c, --context string     Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use")
  -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:
  app*        Docker App (Docker Inc., v0.9.1-beta3)
  builder     Manage builds
  buildx*     Docker Buildx (Docker Inc., v0.8.2-docker)
  compose*    Docker Compose (Docker Inc., v2.6.0)
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  image       Manage images
  manifest    Manage Docker image manifests and manifest lists
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  scan*       Docker Scan (Docker Inc., v0.17.0)
  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.

To get more help with docker, check out our guides at https://docs.docker.com/go/guides/

[root@ecs-214025 admin]# docker version --help

Usage:  docker version [OPTIONS]

Show the Docker version information

Options:
  -f, --format string       Format the output using the given Go template
      --kubeconfig string   Kubernetes config file
[root@ecs-214025 admin]# 

官网帮助文档

:::info
docker文档:https://docs.docker.com/
docker参考文档:https://docs.docker.com/reference/
:::
image.png

镜像命令

docker images 查看所有本地的主机上的镜像

:::info
docker参考文档:https://docs.docker.com/reference/
:::
image.png
image.png
image.png

[root@ecs-214025 admin]# 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 image IDs
[root@ecs-214025 admin]# 

[root@ecs-214025 admin]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    feb5d9fea6a5   9 months ago   13.3kB
[root@ecs-214025 admin]# 

image.png

docker search 搜索镜像

[root@ecs-214025 admin]# docker search --help

Usage:  docker search [OPTIONS] TERM

Search the Docker Hub for images

Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print search using a Go template
      --limit int       Max number of search results (default 25)
      --no-trunc        Don't truncate output

[root@ecs-214025 admin]# docker search mysql
NAME                           DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                          MySQL is a widely used, open-source relation…   12769     [OK]       
mariadb                        MariaDB Server is a high performing open sou…   4906      [OK]       
percona                        Percona Server is a fork of the MySQL relati…   579       [OK]       
phpmyadmin                     phpMyAdmin - A web interface for MySQL and M…   557       [OK]       
bitnami/mysql                  Bitnami MySQL Docker Image                      71                   [OK]
linuxserver/mysql-workbench                                                    37                   
linuxserver/mysql              A Mysql container, brought to you by LinuxSe…   35                   
ubuntu/mysql                   MySQL open source fast, stable, multi-thread…   34                   
circleci/mysql                 MySQL is a widely used, open-source relation…   26                   
google/mysql                   MySQL server for Google Compute Engine          21                   [OK]
rapidfort/mysql                RapidFort optimized, hardened image for MySQL   13                   
vmware/harbor-db               Mysql container for Harbor                      10                   
bitnami/mysqld-exporter                                                        3                    
ibmcom/mysql-s390x             Docker image for mysql-s390x                    2                    
vitess/mysqlctld               vitess/mysqlctld                                1                    [OK]
newrelic/mysql-plugin          New Relic Plugin for monitoring MySQL databa…   1                    [OK]
nasqueron/mysql                                                                1                    [OK]
mirantis/mysql                                                                 0                    
docksal/mysql                  MySQL service images for Docksal - https://d…   0                    
drud/mysql-local-57            ddev mysql local container                      0                    
drud/mysql                                                                     0                    
drud/mysql-docker-local-57     This repo has been deprecated, new tags are …   0                    
drud/mysql-docker-local        docker containers for local womysql rk          0                    [OK]
cimg/mysql                                                                     0                    
silintl/mysql-backup-restore   Simple docker image to perform mysql backups…   0                    [OK]
[root@ecs-214025 admin]# 

image.png

docker pull 下载镜像

[root@ecs-214025 admin]# docker pull --help

Usage:  docker pull [OPTIONS] NAME[:TAG|@DIGEST]

Pull an image or a repository from a registry

Options:
  -a, --all-tags                Download all tagged images in the repository
      --disable-content-trust   Skip image verification (default true)
      --platform string         Set platform if server is multi-platform capable
  -q, --quiet                   Suppress verbose output
[root@ecs-214025 admin]# 

默认最新版本下载

[root@ecs-214025 admin]# docker pull mysql
Using default tag: latest
latest: Pulling from library/mysql
824b15f81d65: Pull complete 
c559dd1913db: Pull complete 
e201c19614e6: Pull complete 
f4247e8f6125: Pull complete 
dc9fefd8cfb5: Pull complete 
32cfafb64fee: Pull complete 
c9caad7ee0fc: Pull complete 
c8ed38840e96: Pull complete 
5a172dc2c4c7: Pull complete 
d800b83bd024: Pull complete 
b20e07df03fa: Pull complete 
22e8ad187ab6: Pull complete 
Digest: sha256:bed914af3f2dea400c4bc83136d6b3a8cf7edcf96f5c08bbbdec8a10cc021a5d
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest
[root@ecs-214025 admin]# 

image.png

指定版本下载

:::info
注:指定的版本必须是dockerhub上有的版本
:::
image.png

[root@ecs-214025 admin]# docker pull mysql:5.7
5.7: Pulling from library/mysql
824b15f81d65: Already exists 
c559dd1913db: Already exists 
e201c19614e6: Already exists 
f4247e8f6125: Already exists 
dc9fefd8cfb5: Already exists 
32cfafb64fee: Already exists 
c9caad7ee0fc: Already exists 
f55f87b960ba: Pull complete 
459044ae96d1: Pull complete 
0dc62f07e93a: Pull complete 
f2b9a5e10609: Pull complete 
Digest: sha256:60adb6e158c126a6cd93aa7d4aaee15bcf1beae224c04363cbf088193a696802
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7
[root@ecs-214025 admin]# 

[root@ecs-214025 admin]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
mysql         5.7       74a6a7ec181f   2 days ago     462MB
mysql         latest    968083d5be36   2 days ago     524MB
hello-world   latest    feb5d9fea6a5   9 months ago   13.3kB
[root@ecs-214025 admin]# 

docker rmi 删除镜像

[root@ecs-214025 admin]# docker rmi --help

Usage:  docker rmi [OPTIONS] IMAGE [IMAGE...]

Remove one or more images

Options:
  -f, --force      Force removal of the image
      --no-prune   Do not delete untagged parents
[root@ecs-214025 admin]# 

image.png

[root@ecs-214025 admin]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
mysql         5.7       74a6a7ec181f   2 days ago     462MB
mysql         latest    968083d5be36   2 days ago     524MB
hello-world   latest    feb5d9fea6a5   9 months ago   13.3kB
[root@ecs-214025 admin]# docker rmi -f 74a6a7ec181f
Untagged: mysql:5.7
Untagged: mysql@sha256:60adb6e158c126a6cd93aa7d4aaee15bcf1beae224c04363cbf088193a696802
Deleted: sha256:74a6a7ec181f30ef057aceb9ee70680497cde2128e2f0e8b7895dcefe5684927
Deleted: sha256:4f268a148aa204b933927eb1532b83791d39988fc993ffe43e29f636df521d00
Deleted: sha256:28bad881942f22f0793adedead36611ee11897b0a152422f23b94e7a39f87212
Deleted: sha256:fa442bd51a85337cb05868b9b433b3f566f5d7daf7ca2e8acf5ffb7f878f3ef3
Deleted: sha256:a72adb381cd9116f59c8bbc41331dd3813ec0f978faa6e68173d0faf24b72957
[root@ecs-214025 admin]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
mysql         latest    968083d5be36   2 days ago     524MB
hello-world   latest    feb5d9fea6a5   9 months ago   13.3kB
[root@ecs-214025 admin]# 

容器命令

:::info
说明:有了镜像才可以创建容器,下载一个centos镜像测试学习
:::

[root@ecs-214025 admin]# docker pull centos
Using default tag: latest
latest: Pulling from library/centos
a1d0c7532777: Pull complete 
Digest: sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177
Status: Downloaded newer image for centos:latest
docker.io/library/centos:latest
[root@ecs-214025 admin]# 

docker run 新建容器并启动

image.png

[root@ecs-214025 admin]# 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)
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device list       Block IO weight (relative device weight) (default [])
      --cap-add list                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the container
      --cgroupns string                Cgroup namespace to use (host|private)
                                       'host':    Run the container in the Docker host's cgroup namespace
                                       'private': Run the container in its own private cgroup namespace
                                       '':        Use the cgroup namespace as configured by the
                                                  default-cgroupns-mode option on the daemon (default)
      --cidfile string                 Write the container ID to the file
      --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
      --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)
  -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
      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
      --device-read-bps list           Limit read rate (bytes per second) from a device (default [])
      --device-read-iops list          Limit read rate (IO per second) from a device (default [])
      --device-write-bps list          Limit write rate (bytes per second) to a device (default [])
      --device-write-iops list         Limit write rate (IO per second) to a device (default [])
      --disable-content-trust          Skip image verification (default true)
      --dns list                       Set custom DNS servers
      --dns-option list                Set DNS options
      --dns-search list                Set custom DNS search domains
      --domainname string              Container NIS domain name
      --entrypoint string              Overwrite the default ENTRYPOINT of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --gpus gpu-request               GPU devices to add to the container ('all' to pass all GPUs)
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)
      --health-retries int             Consecutive failures needed to report unhealthy
      --health-start-period duration   Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to run (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
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (e.g., 92:d0:c6:0a:29:33)
  -m, --memory bytes                   Memory limit
      --memory-reservation bytes       Memory soft limit
      --memory-swap bytes              Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int          Tune container memory swappiness (0 to 100) (default -1)
      --mount mount                    Attach a filesystem mount to the container
      --name string                    Assign a name to the container
      --network network                Connect a container to a network
      --network-alias list             Add network-scoped alias for the container
      --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)
      --platform string                Set platform if server is multi-platform capable
      --privileged                     Give extended privileges to this container
  -p, --publish list                   Publish a container's port(s) to the host
  -P, --publish-all                    Publish all exposed ports to random ports
      --pull string                    Pull image before running ("always"|"missing"|"never") (default "missing")
      --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
      --shm-size bytes                 Size of /dev/shm
      --sig-proxy                      Proxy received signals to the process (default true)
      --stop-signal string             Signal to stop a container (default "SIGTERM")
      --stop-timeout int               Timeout (in seconds) to stop a container
      --storage-opt list               Storage driver options for the container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -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
      --volume-driver string           Optional volume driver for the container
      --volumes-from list              Mount volumes from the specified container(s)
  -w, --workdir string                 Working directory inside the container
[root@ecs-214025 admin]# 

启动并进入容器

image.png

[root@ecs-214025 admin]# docker run -it centos /bin/bash
[root@efca76557f9e /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@efca76557f9e /]# exit
exit
[root@ecs-214025 admin]# ls
[root@ecs-214025 admin]# 

docker ps 列出当前正在运行的容器

image.png

[root@ecs-214025 admin]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@ecs-214025 admin]# docker ps -a
CONTAINER ID   IMAGE         COMMAND       CREATED         STATUS                     PORTS     NAMES
efca76557f9e   centos        "/bin/bash"   2 minutes ago   Exited (0) 2 minutes ago             loving_franklin
d00f34be87a8   hello-world   "/hello"      10 days ago     Exited (0) 10 days ago               festive_volhard
[root@ecs-214025 admin]# 

退出容器

image.png

[root@ecs-214025 admin]# docker run -it centos /bin/bash
[root@3e36a6576729 /]# exit
exit
[root@ecs-214025 admin]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@ecs-214025 admin]# docker run -it centos /bin/bash
[root@d4a19059598d /]# [root@ecs-214025 admin]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
d4a19059598d   centos    "/bin/bash"   15 seconds ago   Up 14 seconds             xenodochial_rhodes
[root@ecs-214025 admin]# 

删除容器

image.png

[root@ecs-214025 admin]# docker ps -a
CONTAINER ID   IMAGE         COMMAND                  CREATED          STATUS                      PORTS     NAMES
a8a77de449c2   centos        "/bin/bash"              5 minutes ago    Up 5 minutes                          naughty_almeida
ae69970dde78   centos        "/bin/bash"              5 minutes ago    Exited (0) 5 minutes ago              amazing_mcnulty
a67acc36a208   mysql         "docker-entrypoint.s…"   6 minutes ago    Exited (1) 6 minutes ago              lucid_gould
dd9bd6f1e8b7   hello-world   "/hello"                 6 minutes ago    Exited (0) 6 minutes ago              angry_ritchie
460730bd7375   centos        "/bin/bash"              8 minutes ago    Exited (0) 8 minutes ago              zealous_noether
1e4d0d354ba3   centos        "/bin/bash"              9 minutes ago    Up 9 minutes                          charming_goodall
52cf4f724753   centos        "/bin/bash"              9 minutes ago    Exited (0) 9 minutes ago              determined_swirles
fbd4ed6d1dc7   centos        "/bin/bash"              10 minutes ago   Exited (0) 10 minutes ago             naughty_edison
9f24dcd82441   hello-world   "/hello"                 10 minutes ago   Exited (0) 10 minutes ago             charming_blackburn
f5345f0fc3e2   mysql         "docker-entrypoint.s…"   10 minutes ago   Exited (1) 10 minutes ago             sad_diffie
d4a19059598d   centos        "/bin/bash"              14 minutes ago   Up 13 minutes                         xenodochial_rhodes
3e36a6576729   centos        "/bin/bash"              14 minutes ago   Exited (0) 14 minutes ago             nostalgic_benz
efca76557f9e   centos        "/bin/bash"              18 minutes ago   Exited (0) 18 minutes ago             loving_franklin
d00f34be87a8   hello-world   "/hello"                 10 days ago      Exited (0) 10 days ago                festive_volhard
[root@ecs-214025 admin]# docker rm d00f34be87a8
d00f34be87a8
[root@ecs-214025 admin]# docker rm d4a19059598d
Error response from daemon: You cannot remove a running container d4a19059598d7af42bf125e08d716de8f84e3d240b70740d7011daf124ced54c. Stop the container before attempting removal or force remove
[root@ecs-214025 admin]# docker rm -f d4a19059598d
d4a19059598d
[root@ecs-214025 admin]# docker rm -f $(docker ps -aq)
a8a77de449c2
ae69970dde78
a67acc36a208
dd9bd6f1e8b7
460730bd7375
1e4d0d354ba3
52cf4f724753
fbd4ed6d1dc7
9f24dcd82441
f5345f0fc3e2
3e36a6576729
efca76557f9e
[root@ecs-214025 admin]# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@ecs-214025 admin]# 


启动、停止、重启、杀死容器

image.png

[root@ecs-214025 admin]# docker run -it centos
[root@3979fe550535 /]# exit
exit
[root@ecs-214025 admin]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@ecs-214025 admin]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
3979fe550535   centos    "/bin/bash"   13 seconds ago   Exited (0) 6 seconds ago             flamboyant_feynman
[root@ecs-214025 admin]# docker start 3979fe550535
3979fe550535
[root@ecs-214025 admin]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS        PORTS     NAMES
3979fe550535   centos    "/bin/bash"   27 seconds ago   Up 1 second             flamboyant_feynman
[root@ecs-214025 admin]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS         PORTS     NAMES
3979fe550535   centos    "/bin/bash"   34 seconds ago   Up 8 seconds             flamboyant_feynman
[root@ecs-214025 admin]# docker stop 3979fe550535
3979fe550535
[root@ecs-214025 admin]# docker ps 
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@ecs-214025 admin]# 

后台启动容器

image.png

[root@ecs-214025 admin]# docker run -d centos
e7d063339fab51390a265e1315f881cd7b498b335cecbfb1005c6ae48b4be655
[root@ecs-214025 admin]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@ecs-214025 admin]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                     PORTS     NAMES
e7d063339fab   centos    "/bin/bash"   9 seconds ago   Exited (0) 8 seconds ago             bold_curran
3979fe550535   centos    "/bin/bash"   9 minutes ago   Exited (0) 8 minutes ago             flamboyant_feynman
[root@ecs-214025 admin]# 

docker logs 查看日志

[root@ecs-214025 admin]# 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:37Z) or relative (e.g. 42m for 42 minutes)
  -n, --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:37Z) or relative (e.g. 42m for 42 minutes)
[root@ecs-214025 admin]# 

image.png

[root@ecs-214025 admin]# docker run -d centos /bin/sh -c "while true;do echo zhangyq;sleep 1;done"
41df94846bb8000b7b9c18229218ff89f51dcd5b5d432e3b2a13f9682d405063
[root@ecs-214025 admin]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
41df94846bb8   centos    "/bin/sh -c 'while t…"   3 seconds ago   Up 2 seconds             nifty_brown
[root@ecs-214025 admin]# docker logs -ft --tail 10 41df94846bb8
2022-06-26T07:50:42.553941744Z zhangyq
2022-06-26T07:50:43.555823911Z zhangyq
2022-06-26T07:50:44.557606929Z zhangyq
2022-06-26T07:50:45.559430794Z zhangyq
2022-06-26T07:50:46.561231890Z zhangyq
2022-06-26T07:50:47.563019986Z zhangyq
2022-06-26T07:50:48.564800639Z zhangyq
2022-06-26T07:50:49.566620408Z zhangyq
2022-06-26T07:50:50.568467744Z zhangyq

docker top 查看容器中进程信息

image.png

[root@ecs-214025 admin]# docker top 41df94846bb8
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                11728               11709               0                   15:50               ?                   00:00:00            /bin/sh -c while true;do echo zhangyq;sleep 1;done
root                12440               11728               0                   15:56               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
[root@ecs-214025 admin]# 

docker inspect 查看容器的元数据

[root@ecs-214025 admin]# docker inspect --help

Usage:  docker inspect [OPTIONS] NAME|ID [NAME|ID...]

Return low-level information on Docker objects

Options:
  -f, --format string   Format the output using the given Go template
  -s, --size            Display total file sizes if the type is container
      --type string     Return JSON for specified type
[root@ecs-214025 admin]# 

image.png

[root@ecs-214025 admin]# docker inspect 41df94846bb8
[
    {
        "Id": "41df94846bb8000b7b9c18229218ff89f51dcd5b5d432e3b2a13f9682d405063",
        "Created": "2022-06-26T07:50:18.229996076Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true;do echo zhangyq;sleep 1;done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 11728,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2022-06-26T07:50:18.508532926Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
        "ResolvConfPath": "/var/lib/docker/containers/41df94846bb8000b7b9c18229218ff89f51dcd5b5d432e3b2a13f9682d405063/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/41df94846bb8000b7b9c18229218ff89f51dcd5b5d432e3b2a13f9682d405063/hostname",
        "HostsPath": "/var/lib/docker/containers/41df94846bb8000b7b9c18229218ff89f51dcd5b5d432e3b2a13f9682d405063/hosts",
        "LogPath": "/var/lib/docker/containers/41df94846bb8000b7b9c18229218ff89f51dcd5b5d432e3b2a13f9682d405063/41df94846bb8000b7b9c18229218ff89f51dcd5b5d432e3b2a13f9682d405063-json.log",
        "Name": "/nifty_brown",
        "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,
            "CgroupnsMode": "host",
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "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,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/a0c8c22317ae9e7c257e8d7b5f8e93b01c549a81a148c4dbe93db16b2f2714ef-init/diff:/var/lib/docker/overlay2/430064331e1eb0d49d9538e7642e8d52ed510cad38e5de1a4e5b731ae1f5fc92/diff",
                "MergedDir": "/var/lib/docker/overlay2/a0c8c22317ae9e7c257e8d7b5f8e93b01c549a81a148c4dbe93db16b2f2714ef/merged",
                "UpperDir": "/var/lib/docker/overlay2/a0c8c22317ae9e7c257e8d7b5f8e93b01c549a81a148c4dbe93db16b2f2714ef/diff",
                "WorkDir": "/var/lib/docker/overlay2/a0c8c22317ae9e7c257e8d7b5f8e93b01c549a81a148c4dbe93db16b2f2714ef/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "41df94846bb8",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "while true;do echo zhangyq;sleep 1;done"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20210915",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "9d602301f20838f3fd56f2591106c5b06d2a09fde19d7900fc3df9253004a895",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/9d602301f208",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "323227aed766d91bb41157c6069a14ec5f27fc5de90a80eaa2ea5e1814b82ae3",
            "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": "c1e17e5918804d242b90300db0185948dc8b70b58708439899d4497f260c3136",
                    "EndpointID": "323227aed766d91bb41157c6069a14ec5f27fc5de90a80eaa2ea5e1814b82ae3",
                    "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
                }
            }
        }
    }
]
[root@ecs-214025 admin]# 

进入当前正在运行的容器

docker exec

[root@ecs-214025 admin]# docker exec --help

Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

Options:
  -d, --detach               Detached mode: run command in the background
      --detach-keys string   Override the key sequence for detaching a container
  -e, --env list             Set environment variables
      --env-file list        Read in a file of environment variables
  -i, --interactive          Keep STDIN open even if not attached
      --privileged           Give extended privileges to the command
  -t, --tty                  Allocate a pseudo-TTY
  -u, --user string          Username or UID (format: <name|uid>[:<group|gid>])
  -w, --workdir string       Working directory inside the container
[root@ecs-214025 admin]# 

image.png

[root@ecs-214025 admin]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
41df94846bb8   centos    "/bin/sh -c 'while t…"   22 minutes ago   Up 22 minutes             nifty_brown
[root@ecs-214025 admin]# docker exec -it 41df94846bb8 /bin/bash
[root@41df94846bb8 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@41df94846bb8 /]# ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 07:50 ?        00:00:00 /bin/sh -c while true;do echo zhangyq;sleep 1;done
root      1378     0  0 08:13 pts/0    00:00:00 /bin/bash
root      1399     1  0 08:13 ?        00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
root      1400  1378  0 08:13 pts/0    00:00:00 ps -ef
[root@41df94846bb8 /]# 

docker attach

[root@ecs-214025 admin]# docker attach --help

Usage:  docker attach [OPTIONS] CONTAINER

Attach local standard input, output, and error streams to a running container

Options:
      --detach-keys string   Override the key sequence for detaching a container
      --no-stdin             Do not attach STDIN
      --sig-proxy            Proxy all received signals to the process (default true)
[root@ecs-214025 admin]# 

image.png

[root@ecs-214025 admin]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
41df94846bb8   centos    "/bin/sh -c 'while t…"   34 minutes ago   Up 34 minutes             nifty_brown
[root@ecs-214025 admin]# docker attach 41df94846bb8
zhangyq
zhangyq
zhangyq
zhangyq
zhangyq
^Czhangyq
zhangyq
zhangyq

exec和attach的区别

image.png

docker cp 从容器内拷贝文件到主机

image.png
image.png

[root@ecs-214025 admin]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@ecs-214025 admin]# docker run -it centos /bin/bash
[root@e22c8e5badd6 /]# [root@ecs-214025 admin]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
e22c8e5badd6   centos    "/bin/bash"   19 seconds ago   Up 18 seconds             goofy_franklin
[root@ecs-214025 admin]# docker attach e22c8e5badd6
[root@e22c8e5badd6 /]# cd /home 
[root@e22c8e5badd6 home]# ls
[root@e22c8e5badd6 home]# touch test.java
[root@e22c8e5badd6 home]# ls -l
total 0
-rw-r--r-- 1 root root 0 Jun 26 09:00 test.java
[root@e22c8e5badd6 home]# exit
exit
[root@ecs-214025 admin]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED              STATUS                      PORTS     NAMES
e22c8e5badd6   centos    "/bin/bash"   About a minute ago   Exited (0) 10 seconds ago             goofy_franklin
[root@ecs-214025 admin]# docker cp e22c8e5badd6:/home/test.java /home/admin
[root@ecs-214025 admin]# ll
total 0
-rw-r--r-- 1 root root 0 Jun 26 17:00 test.java
[root@ecs-214025 admin]# 

小结

image.png
image.png
image.png

标签:--,admin,214025,ecs,Docker,常用命令,docker,root,030
来源: https://www.cnblogs.com/wl3pb/p/16439858.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有