docker问答

文章目录

docker问答


如何知道docker有那些指令?

  • 可以执行docker --help
Usage:	docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default
                           "/home/hwj/.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
                           "/home/hwj/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default
                           "/home/hwj/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default
                           "/home/hwj/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

Management Commands:
  builder     Manage builds
  config      Manage Docker configs
  container   Manage containers
  engine      Manage the docker engine
  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.


如何重启docker daemon?

sudo systemctl daemon-reload


如何重启docker服务?

sudo systemctl restart docker


如何让docker 容器自启动?

  • 在run的时候加上–restart always参数或通过update命令加上–restart always

如何卸载docker?

  • ubuntu下举例:

1 Uninstall the Docker CE package:

$ sudo apt-get purge docker-ce

2 Images, containers, volumes, or customized configuration files on your host are not automatically removed. To delete all images, containers, and volumes:

$ sudo rm -rf /var/lib/docker

3 You must delete any edited configuration files manually.


当我们在一个运行的容器中修改了一些配置后,如何将其保存为一个新的镜像?

  • 可以使用commit命令
Usage:	docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

Create a new image from a container's changes

Options:
  -a, --author string    Author (e.g., "John Hannibal Smith
                         <[email protected]>")
  -c, --change list      Apply Dockerfile instruction to the created image
  -m, --message string   Commit message
  -p, --pause            Pause container during commit (default true)

如果想把镜像或容器导出给其他人使用,如何操作?

  • 可以使用export或save命令,区别是export是持久化容器,而save是持久化镜像
Usage:	docker export [OPTIONS] CONTAINER

Export a container's filesystem as a tar archive

Options:
  -o, --output string   Write to a file, instead of STDOUT
 

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

Save one or more images to a tar archive (streamed to STDOUT by default)

Options:
  -o, --output string   Write to a file, instead of STDOUT


如何把别人导出的镜像或容器文件加载进来?

  • 可以通过命令load或import
  • 实际上,既可以使用docker load命令来导入镜像库存储文件到本地镜像库,也可以使用docker import命令来导入一个容器快照到本地镜像库。两者的区别在于容器快照将会丢弃所有的历史记录和元数据信息,而镜像存储文件将保存完整记录,体积也会更大。此外从容器快照文件导入时,也可以重新指定标签等元数据。
Usage:	docker load [OPTIONS]

Load an image from a tar archive or STDIN

Options:
  -i, --input string   Read from tar archive file, instead of STDIN
  -q, --quiet          Suppress the load output

Usage:	docker import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]

Import the contents from a tarball to create a filesystem image

Options:
  -c, --change list      Apply Dockerfile instruction to the created image
  -m, --message string   Set commit message for imported image



如何发布一个镜像到docker hub?

  • 先到dockerhub官网创建一个Repositories,比如创建了名为basic的Repositories,如果用户名为abc,那Repositories则为abc/basic

  • 然后使用docker commit从要发布的容器中创建一个镜像,比如这里为

    docker commit 容器id abc/basic:111
    

    这里的abc/basic一定要跟之前在dockerhub上创建的一样后面才可以发布成功

  • 创建成功后通过docker images即可看到abc/basic:111这个镜像

  • 之后使用docker login 登录dockerhub,输入用户名和密码(login默认的服务地址为 docker.io)

    docker login -u abc -p 密码
    
  • 登录成功后就可以用发布到dockerhub上了

    docker push abc/basic:111
    

    发布到其他仓库过程也类似,就是在login时需要写上服务地址,如阿里云的为 registry.cn-hangzhou.aliyuncs.com,具体的可以参考阿里云官网的说明


如果容器已经在跑了,但是想更改一些配置,如何操作?

  • 可以使用命令update
Usage:	docker update [OPTIONS] CONTAINER [CONTAINER...]

Update configuration of one or more containers

Options:
      --blkio-weight uint16        Block IO (relative weight), between 10
                                   and 1000, or 0 to disable (default 0)
      --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 the CPU real-time period in
                                   microseconds
      --cpu-rt-runtime int         Limit the 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)
      --kernel-memory bytes        Kernel memory limit
  -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
      --restart string             Restart policy to apply when a
                                   container exits

比如为容器添加自启动:docker update --restart always <containerid>
关闭容器自启动:docker update --restart=no <containerid>


如何为镜像加速?

  • 新版的 Docker 使用 /etc/docker/daemon.json(Linux) 或者 %programdata%\docker\config\daemon.json(Windows) 来配置 Daemon。

  • 请在该配置文件中加入(没有该文件的话,请先建一个):

       {
          "registry-mirrors": ["http://hub-mirror.c.163.com"]
        }
    
  • 之后执行

sudo systemctl daemon-reload
sudo systemctl restart docker


如何制作一个简单的jdk8镜像用于服务运行?

# 第一条指令,指定基础镜像
FROM centos
# 作者信息
MAINTAINER hwj

#自定义信息
LABEL description="修改时区为东八区" version="1.0.1"

# 复制文件,本地已解压好jdk1.8.0_181
COPY jdk1.8.0_181

# 修改时区为东八区
RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime 
RUN echo "Asia/Shanghai" >> /etc/timezone

# 配置环境变量
ENV JAVA_HOME=/jdk1.8.0_181
ENV PATH=$JAVA_HOME/bin:$PATH

如何进入docker容器内部?

  • 通过exec: docker exec -it bash
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
  -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

在执行远程复制文件scp时经常发生"坏的解释器:没有那个文件或目录",该如何解决?

  • 由于shell文件是从windows拷贝过来的,因此多了\r,只要执行以下命令即可(比如对于build.sh文件)

sed -i ‘s/\r$//’ build.sh


docker中的容器时区跟宿主机时区不一致,相差8小时,该如何解决?

  1. 如果是自己构建的镜像则在编写Dockerfile时增加如下命令:

RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo “Asia/Shanghai” >> /etc/timezone

  1. 如果是他人的镜像则可以在run命令中增加如下参数后重新run:

-v /etc/localtime:/etc/localtime:ro

  1. 如果是docker容器内时区正确,宿主机也是正确的,但服务代码里获取的时间还是UTC的(比如springboot服务),那么请在Dockerfile中增加时区同时在run时增加时区卷:

RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo “Asia/Shanghai” >> /etc/timezone

-v /etc/localtime:/etc/localtime:ro


如果容器内想相互访问,比如容器a内部需要访问容器b,该怎么办?

  • 一种是在容器a内部配置容器b的内部ip,一种是在run里加上–link参数来连接容器b
  • 假如容器b在run时指定名字为–name myname,那么容器a在run时加上–link myname即可,这样在容器a的配置文件中就可以直接使用myname,而不是容器b的内部ip地址,因为内部ip地址是可能经常变换的。

有些文件我想从容器内部拷出到宿主机,该怎么操作?

  • 可以通过cp命令
Usage:  docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
        docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

Copy files/folders between a container and the local filesystem

Options:
  -a, --archive       Archive mode (copy all uid/gid information)
  -L, --follow-link   Always follow symbol link in SRC_PATH
  • 例如

docker cp tmp-nginx-container:/etc/nginx/nginx.conf /host/path/nginx.conf

  • 则是将名为 tmp-nginx-container的容器内的/etc/nginx/nginx.conf拷贝到宿主机的/host/path/nginx.conf

产生docker0: iptables: No chain/target/match by that name错误该怎么办?

  • 产生这个可能是由于执行了iptables -F或其他操作把docker给清除了,此时需要重启下docker服务:systemctl restart docker,之后iptables -L即可看到chain docker。

产生Error response from daemon: Get https://registry-1.docker.io/v2/: dial tcp: lookup registry-1.docker.io on [::1]:53: read udp [::1]:48987->[::1]:53: read: connection refused 错误该怎么办?

  • 产生此种错误一般是由于网络问题或是dns解析出错

  • 如果是网络问题,有可能是因为墙的问题,那么配置一下阿里云的镜像即可(见此文章中的镜像加速)

  • 如果是dns的问题,则需要修改dns

  • 此处以ubuntu为例,当我们cat /etc/resolv.conf时可以明显看到有一段警告

    # Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
    # DO NOT EDIT THIS FILE BY HAND – YOUR CHANGES WILL BE OVERWRITTEN

  • 也就是直接修改这个文件的话那么重启后修改将被覆盖,因此我们不要手动去修改这个文件。有两种办法进行修改:

  1. 在/etc/network/interfaces的最后添加

    	dns-nameservers 114.114.114.114
        dns-nameservers 8.8.8.8
    

    重启后即可生效,可查看/etc/resolv.conf里的内容。

  2. 在/etc/resolvconf/resolv.conf.d/base里插入

    	nameserver 114.114.114.114
        nameserver 8.8.8.8
    

    然后执行一下命令即可

     resolvconf -u
    

Docker容器跑完就退出了,查看日志发现容器内要运行的服务已经启动成功?

  • 产生这个可能是容器内的服务是在后台运行的,容器必须有一个在前台运行的程序,否则docker就认为这个容器已经挂了,便退出了。因此容器内请至少让一个服务在前台运行。
  • docker run 的时候加上-it,一般会直接进入bash,此时不主动exit退出,则容器还会运行,如果想一直运行则加上-d让其在后台运行,进入容器内部用ps aux查看容器发现进程id为1的就是/bin/bash的程序,只要进程id为1的不被杀死,那么容器就不会退出。

如何让非root用户使用docker?

  • 在使用docker时,如果是非root用户,执行每个命令都需要加上sudo,超级麻烦,那么只需要执行下面一行命令就可以让非root用户加入docker组:
    If you would like to use Docker as a non-root user, you should now consider
    adding your user to the “docker” group with something like:
    sudo usermod -aG docker <user>
    
  • 执行后记得退出当前用户后再次登录即可看到效果

如何查看docker中容器的内存使用情况及限制容器的内存?

  • 可以通过docker stats命令输出各个容器的内存使用情况,如下图

在这里插入图片描述

  • 可以看到内存都是没有限制的,默认使用物理机的所有内存,为了不让单个服务由于异常占用全部内存,有必要对内存做一些限制,
  • 可以在run命令中添加参数 -m 512M --memory-swap=1G,来限制最大容器使用的物理内容为512M,并且可以使用(1G-512M)512M的swap,如果–memory-swap不设置的话默认是物理内存的2倍

参考

docker0: iptables: No chain/target/match by that name - newtelcom的专栏 - CSDN博客
https://blog.csdn.net/newtelcom/article/details/79548152
Ubuntu下修改为永久DNS的方法 - 地球上的我 - 博客园
https://www.cnblogs.com/zjdeblog/p/6128461.html

发布了126 篇原创文章 · 获赞 37 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/huweijian5/article/details/86382062