Docker基础篇使用

Docker基础篇使用笔记

Centos 7下Docker的安装

Docker使用

docker常用镜像命令

docker常用容器命令

docker镜像打包提交

Dockerfile构建镜像

dockerfile脚本简单编写

docker镜像推送云仓库

docker-compose编排管理多个组件

编写docker-compose.yml

Docker是一种遵从Apache2.0协议开源的Linux容器管理解决方案,它通过进程和进程通信技术对操作系统的文件资源和网络的进行隔离,实现了包含文件资源、系统资源(shell环境等)以及网络资源的容器创建和管理。

可简单理解为一种沙盒 。每个容器内运行一个应用,不同的容器之间相互隔离,容器之间也可以建立通信机制。容器的创建和停止都十分快速,资源需求远远低于虚拟机。

镜像,类似虚拟机镜像,比较精简

容器,镜像运行实例

仓库,存放镜像

Centos 7下Docker的安装

官方文档https://docs.docker.com/engine/install/

#通过 **uname -r** 命令查看你当前的内核版本,内核版本要高于3.10
uname -r

#使用 root 权限登录 Centos。确保 yum 包更新到最新。
sudo yum update

#卸载旧版本(如果安装过旧版本的话)
sudo yum remove docker  docker-common docker-selinux docker-engine

#安装需要的软件包, yum-util 提供yum-config-manager功能,另外两个是devicemapper驱动依赖的
sudo yum install -y yum-utils device-mapper-persistent-data lvm2

#设置yum源
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

#可以查看所有仓库中所有docker版本,并选择特定版本安装
yum list docker-ce --showduplicates | sort -r

#安装docker,例如sudo yum install docker-ce-17.12.1.ce
sudo yum install <FQPN>

#启动并加入开机启动
sudo systemctl start docker
sudo systemctl enable docker

#管理服务
systemctl start|stop|restart docker

#验证安装是否成功(有client和service两部分表示docker安装启动都成功了)
docker version

docker-compose安装,通过docker-compose.yml可以便捷的批量管理docker容器

#安装太慢可以用梯子离线下载安装
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

sudo chmod +x /usr/local/bin/docker-compose

#如果docker-compose命令运行失败,链接安装路径
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

安装完成后查看版本

image-20200614135246380

配置阿里云容器镜像加速地址(注册阿里云-->控制台-->容器镜像服务)

sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://xxxxx.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

Docker使用

docker常用镜像命令
#查看docker信息
docker info

#搜索镜像
docker search [IMAGE_NAME]

#拉取docker镜像
docker pull [IMAGE_NAME]:[tag]

#查看本地镜像
docker images -a

#删除镜像
docker rmi -f [IMAGE_ID|IMAGE_NAME]

#删除多个镜像,清空docker rmi -f $(docker images -qa)
docker rmi -f [IMAGE_NAME1]:[tag1] [IMAGE_NAME2]:[tag2]


docker常用容器命令

docker [run|ps] --help

[OPTIONS] docker run [OPTIONS] IMAGE [COMMAND] [ARGS...]
--name "容器名” 为容器指定一个名称
-d, --detach Run container in background and print container ID(后台守护式启动)
-i, --interactive Keep STDIN open even if not attached(交互模式启动容器)
-t, --tty Allocate a pseudo-TTY(-it,运行时新建伪终端容器内部)
-p, --publish list Publish a container's port(s) to the host (随机端口映射)
-P --publish-all Publish all exposed ports to random ports(指定端口映射)

(run没加-d参数交互式运行时,exit容器停止退出,Ctrl+P+Q不停止退出)

[OPTIONS] docker ps [OPTIONS]
-a, --all Show all containers (default shows just running)
-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 list Don't truncate output
-q, --quiet Only display numeric IDs
-s, --size Display total file sizes

常用命令

docker [start|stop|restart|rm|kill] [容器id|[容器NAME]

docker run -d [IMAGE_ID]

#-t加入时间戳,-f跟随最新日志打印,--tail显示最后打印多少条
docker logs -f -t --tail [容器id]

#查看容器内运行的进程
docker top [容器id]

#查看容器Json描述细节
docker inspect [容器id]

#进去容器内部 Exit退出
docker exec -it [容器id] bash #容器外部执行查看docker exec -t d8488064b282 ls -l /var
docker attach [容器id]


#文件从容器复制到宿主机
docker cp 容器ID/容器name:容器目录 当前宿主机的文件
#宿主机文件到容器
docker cp 当前宿主机的文件 容器ID或者容器name:容器目录

#example:docker pull nginx
#启动容器复制配置文件
docker run --name nginx-test -p 80:80 -d nginx
mkdir -p ~/docker/nginx/www ~/docker/nginx/logs ~/docker/nginx/conf ~/docker/nginx/conf.d
docker cp 容器id:/etc/nginx/nginx.conf ~/docker/nginx/conf
docker cp 容器id:/etc/nginx/conf.d/default.conf ~/docker/nginx/conf.d
docker cp 容器id:/usr/share/nginx/html/index.html ~/docker/nginx/www

#运行容器,-v数据卷映射配置,启动nginx容器时,一定要加--net host参数(解释:容器将不会虚拟出自己的网卡,配置自己的IP等,而是使用宿主机的IP和端口,如果不加此参数,nginx相当于是代理nginx镜像的IP及端口,nginx镜像也是独立的虚机)
docker run -d --name nginx-server -p 80:80 --net host -v ~/docker/nginx/conf/nginx.conf:/etc/nginx/nginx.conf -v ~/docker/nginx/logs:/var/log/nginx -v ~/docker/nginx/www:/usr/share/nginx/html -v ~/docker/nginx/conf.d/default.conf:/etc/nginx/conf.d/default.conf nginx

docker [OPTIONS] COMMAND

#docker [OPTIONS] COMMAND
docker --help

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:
  builder     Manage builds
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  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镜像打包提交

docker镜像又一层一层文件系统套娃组成,层级文件系统UnionFS

#将容器打包成镜像
docker commit -a="作者名字" -m="提交信息" 容器id xxxx/nginx:1.01

#IMAGE_ID删除,可能冲突,可以使用IMAGE_NAME删除
docker rmi xxxx/nginx:1.01

Dockerfile构建镜像

构建docker镜像的一系列命令和参数构成的脚本

  • 每条保留字指令必须为大写字母且后面要跟随至少一个参数
  • 指令安装从上到下,顺序执行
  • 每条指令都会创建一个新的镜像层,并对镜像进行提交

执行大致流程:dockerfile --> docker build (多层打包)--> docker run

  1. docker从基础镜像运行一个容器
  2. 执行一条指令并对容器做修改
  3. 执行类似docker commit的操作提交一个新的镜像层
  4. docker再基于刚提交的镜像运行一个新的容器
  5. 执行dockerfile中的下一条指令直到所有指令都执行完成
FROM ubuntu
VOLUME ["~/dateVolumeContainer1","~/dateVolumeContainer2"]
CMD echo "dinished,-------success"
CMD /bin/bash
docker build -f /root/Dockerfile -t  jibny/ubuntu:1.01 .  
docker run -it --name ubuntu1 jibny/ubuntu:1.01 

#--volumes-from,多容器继承共享文件
docker run -it --name ubuntu2 --volumes-from ubuntu1 jibny/ubuntu:1.01
FROM 构建时基于的基础镜像
MAINTAINER 镜像维护者姓名和邮箱地址
RUN 容器构建时需要运行的命令
EXPOSE 当前容器对外暴露出的端口
WORKDIR 指定在创建容器后,终端默认登录的目录
ENV 构建镜像时设置环境变量
ADD 将宿主机目录下的文件拷贝到镜像中,且自动处理URL和解压
COPY 类似ADD,但是不会解压处理,例:COPY src dest|COPY ["src","dest"]
VOLUME 容器数据卷,用于数据保存和持久化工作
CMD 指定容器启动时运行的命令,可以有多个CMD命令只有最后一个生效,会被docker run后面的参数替换
ENTRYPOINT 指定容器启动时运行的命令,docker run后追加
ONBUILD 当构建一个被继承的Dockerfile时运行该命令,父镜像被子镜像继承后父镜像的ONBUILD触发
dockerfile脚本简单编写
FROM centos
MAINTAINER Jibny<zhanjibin99@gmail.com>

ENV MYPATH /usr/local
WORKDIR $MYPATH

RUN yum -y install vim
RUN yum -y net-tools

EXPOSE 80

CMD echo $MYPATH
CMD echo "success----------ok"
CMD /bin/bash
docker build -f  ~/DockerfileCentos -t mycentos:1.01 .

image-20200615170646090

启动容器,测试登录的目录和vim命令

基于centos自定义tomcat镜像

FROM         centos
MAINTAINER    jibny<zhanjibin99@gmail.com>
#把宿主机当前上下文的c.txt拷贝到容器/usr/local/路径下
COPY java.txt /usr/local/java.txt
#把java与tomcat添加到容器中
ADD jdk-8u221-linux-x64.tar.gz /usr/local/
ADD apache-tomcat-9.0.36.tar.gz /usr/local/
#安装vim编辑器
RUN yum -y install vim
#设置工作访问时候的WORKDIR路径,登录落脚点
ENV MYPATH /usr/local
WORKDIR $MYPATH
#配置java与tomcat环境变量
ENV JAVA_HOME /usr/local/jdk1.8.0_221
ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
ENV CATALINA_HOME /usr/local/apache-tomcat-9.0.36
ENV CATALINA_BASE /usr/local/apache-tomcat-9.0.36
ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin
#容器运行时监听的端口
EXPOSE  8080
#启动时运行tomcat
# ENTRYPOINT ["$CATALINA_HOME/bin/startup.sh"]
# CMD ["$CATALINA_HOME/bin/catalina.sh","run"]
CMD $CATALINA_HOME/bin/startup.sh && tail -F $CATALINA_HOME/bin/logs/catalina.out
#构建镜像
docker build -f dockerfile -t mytomcat9:1.01 .

#运行
docker run -d --name mytomcat9 -p 8023:8080 -v ~/docker/tomcat9/webapps:/usr/local/apache-tomcat-9.0.36/webapps -v ~/docker/tomcat9/logs:/usr/local/apache-tomcat-9.0.36/logs --privileged=true mytomcat9:1.01 

image-20200615194746190

docker镜像推送云仓库
$ sudo docker login --username=用户名 registry.cn-hangzhou.aliyuncs.com
$ sudo docker tag [ImageId] registry.cn-hangzhou.aliyuncs.com/jibny/mycentos:[镜像版本号]
$ sudo docker push registry.cn-hangzhou.aliyuncs.com/jibny/mycentos:[镜像版本号]

#拉取镜像
docker pull registry.cn-hangzhou.aliyuncs.com/jibny/mycentos:[镜像版本号]

image-20200615204457260

docker-compose编排管理多个组件

docker-compose的使用非常类似于docker命令的使用,compose命令都需要到docker-compose.yml文件所在的目录下才能执行。

#常用命令
docker-compose up     #命令聚合每个容器的输出,命令退出时,所有容器都将停止。

docker-compose up -d     #在后台启动容器并使它们保持运行。

docker-compose logs -f     #查看该容器的启动的日志打印(日志从头打印)。

docker logs -f container_id     #查看某一容器的启动的日志打印(日志从头打印)。 

docker logs -f --tail 数量词 container_id     #查看某一容器的启动的日志打印(查看最后n条日志打印)。 例:docker logs -f --tail 50 44b 

docker-compose stop     #停止compose服务。

docker-compose restart     #重启compose服务。

docker-compose kill     #kill compose服务。

docker-compose ps    #查看compose服务状态。

docker-compose rm    #删除compose服务。
编写docker-compose.yml

( nginx|tomcat|redis|mysql )(密码:abc.123456)

注意:需要提前拷贝三个配置文件(可以先docker run 镜像,再从容器拷贝到宿主机) 下载

  1. ./nginx/conf/nginx.conf
  2. ./nginx/conf.d/default.conf
  3. ./redis/conf/redis.conf
version: '3'
services:

  nginx:
    restart: always
    image: nginx
    container_name: nginx
    ports:
      - 80:80
      - 443:443
    network_mode: "host"
    volumes:
      - ./nginx/conf/nginx.conf:/etc/nginx/nginx.conf
      - ./nginx/logs:/var/log/nginx 
      - ./nginx/www:/usr/share/nginx/html
      - ./nginx/conf.d/default.conf:/etc/nginx/conf.d/default.conf

  tomcat:
    restart: always
    image: tomcat
    container_name: tomcat
    ports:
      - 8023:8080
    volumes:
      - ./tomcat/webapps/:/usr/local/tomcat/webapps/
    environment:
      TZ: Asia/Shanghai

  redis:
    restart: always
    image: redis
    container_name: redis
    ports:
      - 6379:6379
    command: redis-server /etc/redis/redis.conf
    volumes:
      - ./redis/conf:/etc/redis
      - ./redis/data:/data
      - ./redis/log:/var/log/redis

  mysql:
    restart: always
    image: mysql:5.7.30
    container_name: mysql
    ports:
      - 3306:3306
    environment:
      TZ: Asia/Shanghai
      MYSQL_ROOT_PASSWORD: abc.123456
    command:
      --character-set-server=utf8mb4
      --collation-server=utf8mb4_general_ci
      --explicit_defaults_for_timestamp=true
      --lower_case_table_names=1
      --max_allowed_packet=128M
      --sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO"
    volumes:
      - ./mysql/mysql-data:/var/lib/mysql

当前目录docker-compose up -d 启动测试

image-20200615233549084

Docker基础篇完结,复习了一遍,又花了一天多的时间。无论是dockerfile打包镜像还是docker-compose批量的管理镜像,在组件变多集群部署时候都有点麻烦,期待后面加深学习能解决吧。

posted @ 2020-06-17 01:07  Jibny  阅读(126)  评论(0编辑  收藏  举报