docker basics

installation

  • install on ubuntu
sudo apt install docker.io
  • check whether docker client and server is properly installed
docker version
  • Run docker without sudo
groupadd docker
usermod -aG docker $USER
newgrp docker

image and container

  • image(镜像)相当于虚拟机模板或类
  • container(容器)相当于虚拟机或类的实例

  • check locally available images
docker images
# docker image ls will also work
  • check running containers
docker container ls
  • show both running and stopped container
docker container ls -a
  • remove docker images
docker rmi image_id
# docker image rm image_id will also work
  • start/stop/remove container instances
docker container start container_id
docker container stop container_id
docker container rm container_id
  • run a exutable with docker container from a image
# run a exutable with docker container from a image
# docker container run name.or.id.of.image path.to.exutable parameters
docker run ubuntu echo 'hello world'
# 'hello world'
# if you want docker remove the container after exited, add --rm
# docker container --rm run name.or.id.of.image path.to.exutable
docker run --rm ubuntu echo 'hello world'
# 'hello world'
# If the docker container has a prespecified entry point
# docker run --rm image.with.entry.point parameters
docker run --rm jinyf1998/cowsay.v0 goodbye cold world
# ____________________
#< goodbye cold world >
# --------------------
#        \   ^__^
#         \  (oo)\_______
#            (__)\       )\/\
#                ||----w |
#                ||     ||
  • docker container execdocker container run功能比较类似,区别在于

docker volume (数据卷)

  • external storage
  • 有的时候你希望docker利用宿主机上的存储
  • Docker volumes are directories that are not part of the container’s UFS
# 把当前路径下的programming目录mount到docker container 的/data路径下
# 如果想挂载多个目录,多次指定-v就可以了
docker run -it --rm -v $PWD/programming:/data ubuntu /bin/bash

build customized docker image

  • two ways
    • install dependency in docker interactive terminal, than commit a snapshot of the container with docker commit
    • using Dockerfile, and run docker build
  • 优劣比较https://zzq23.blog.csdn.net/article/details/80571262
  • The docker commit method is not currently recommended, as building with a Dockerfile is far more flexible and powerful
  • 常用Dockerfile 关键字
    • FROM 从那个已有镜像开始构建
    • RUN 后跟在构建镜像的过程中执行的命令
    • ENV 设置环境变量
    • ADD 将building context的文件导入镜像
    • COPYADD的区别在于COPY只从本地获得数据
    • VOLUME 挂载数据卷
    • ENTRYPOINT 运行容器的进入程序
    • CMD 容器运行时执行的命令
  • An example
FROM debian
MAINTAINER John Smith <john@smith.com>
RUN apt-get update && apt-get install -y cowsay fortune
COPY entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]
  • run
# Assume a Dockerfile is present in current directory
docker build -t target.image.name .

docker hub

  • pull docker image from docker hub with docker pull

  • push your docker image to docker hub

    • tag the docker image to your own repo with docker tag
    • run docker push

Reference