Harbor部署及简单应用和Docker Compose语法

Harbor部署及简单应用

Harbor

无论是使用Docker-distribution去自建仓库,还是通过官方镜像跑容器的方式去自建仓库,通过前面的演示我们可以发现其是非常的简陋的,还不如直接使用官方的Docker Hub去管理镜像来得方便,至少官方的Docker Hub能够通过web界面来管理镜像,还能在web界面执行搜索,还能基于Dockerfile利用Webhooks和Automated Builds实现自动构建镜像的功能,用户不需要在本地执行docker build,而是把所有build上下文的文件作为一个仓库推送到github上,让Docker Hub可以从github上去pull这些文件来完成自动构建。

但无论官方的Docker Hub有多强大,它毕竟是在国外,所以速度是最大的瓶颈,我们很多时候是不可能去考虑使用官方的仓库的,但是上面说的两种自建仓库方式又十分简陋,不便管理,所以后来就出现了一个被 CNCF 组织青睐的项目,其名为Harbor。

Harbor简介

虽然Docker官方提供了公共的镜像仓库,但是从安全和效率等方面考虑,部署我们私有环境内的Registry也是非常必要的。

Harbor是由VMware公司开源的企业级的Docker Registry管理项目,相比docker官方拥有更丰富的权限权利和完善的架构设计,适用大规模docker集群部署提供仓库服务。

它主要提供 Dcoker Registry 管理界面UI,可基于角色访问控制,镜像复制, AD/LDAP 集成,日志审核等功能,完全的支持中文。

在这里插入图片描述

Harbor 的主要功能

  • 基于角色的访问控制

    • 用户与Docker镜像仓库通过“项目”进行组织管理,一个用户可以对多个镜像仓库在同一命名空间(project)里有不同的权限。
  • 基于镜像的复制策略

    • 镜像可以在多个Registry实例中复制(可以将仓库中的镜像同步到远程的Harbor,类似于MySQL主从同步功能),尤其适合于负载均衡,高可用,混合云和多云的场景。
  • 图形化用户界面

    • 用户可以通过浏览器来浏览,检索当前Docker镜像仓库,管理项目和命名空间。
  • 支持 AD/LDAP

    • Harbor可以集成企业内部已有的AD/LDAP,用于鉴权认证管理。
  • 镜像删除和垃圾回收

    • Harbor支持在Web删除镜像,回收无用的镜像,释放磁盘空间。image可以被删除并且回收image占用的空间。
  • 审计管理

    • 所有针对镜像仓库的操作都可以被记录追溯,用于审计管理。
  • RESTful API

    • RESTful API 提供给管理员对于Harbor更多的操控, 使得与其它管理软件集成变得更容易。
  • 部署简单

    • 提供在线和离线两种安装工具, 也可以安装到vSphere平台(OVA方式)虚拟设备。Harbor 的所有组件都在 Docker 中部署,所以 Harbor 可使用 Docker Compose 快速部署。

注意: 由于 Harbor 是基于 Docker Registry V2 版本,所以 docker 版本必须 > = 1.10.0 docker-compose >= 1.6.0

Docker Compose(编排工具)

Harbor在物理机上部署是非常难的,而为了简化Harbor的应用,Harbor官方直接把Harbor做成了在容器中运行的应用,而且这个容器在Harbor中依赖类似redis、mysql、pgsql等很多存储系统,所以它需要编排很多容器协同起来工作,因此VMWare Harbor在部署和使用时,需要借助于Docker的单机编排工具(Docker compose)来实现。

Compose是一个用于定义和运行多容器Docker应用程序的工具。使用Compose,您可以使用YAML文件来配置应用程序的服务。然后,通过一个命令,您可以创建并启动配置中的所有服务。

Docker compose官方文档

Harbor 部署

Harbor官方文档
环境说明:

主机名ip地址需要安装的应用
docker192.168.200.140docekr-ce
harbor192.168.200.141docker-ce 、docker-compose、Harbor
harbor主机操作
// 关闭防火墙和selinux
[root@harbor ~# systemctl stop firewalld
[root@harbor ~]# vim /etc/sysconfig/selinux 
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these three values:
[root@harbor ~]# setenforce 0
[root@harbor ~]# reboot

[root@harbor ~]# getenforce 
Disabled
// 配置docker-ce源
[root@harbor yum.repos.d]# curl -o docker-ce.repo https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --  0     0    0     0    0     0      0      0 --:--:--  0100  1919  100  1919    0     0   1265      0  0:00:01  0:00:01 --:--:--  1265
[root@harbor yum.repos.d]# sed -i 's@https://download.docker.com@https://mirrors.tuna.tsinghua.edu.cn/docker-ce@g' docker-ce.repo

// 安装 docker-ce 以及依赖包和工具
[root@harbor ~]# dnf -y install yum-utils device-mapper-persistent-data lvm2
[root@harbor ~]# yum -y install docker-ce --allowerasing

// 安装完成后,使用 docker version 命令查看docker的版本信息
[root@harbor ~]# docker version
Client: Docker Engine - Community
 Version:           20.10.12
 API version:       1.41
 Go version:        go1.16.12
 Git commit:        e91ed57
 Built:             Mon Dec 13 11:45:22 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true


// 配置镜像加速
[root@harbor ~]# mkdir -p /etc/docker
[root@harbor ~]# vi /etc/docker/daemon.json
{
    "registry-mirrors": ["https://7z2g0ixw.mirror.aliyuncs.com"]
}
[root@harbor ~]# systemctl daemon-reload
[root@harbor ~]# systemctl enable --now  docker
Created symlink /etc/systemd/system/multi-user.target.wants/docker.service → /usr/lib/systemd/system/docker.service.

在harbor主机上安装compose 和 harbor

[root@harbor ~]# curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
[root@harbor ~]# chmod +x /usr/local/bin/docker-compose
[root@harbor ~]# docker-compose --version
docker-compose version 1.29.2, build 5becea4c


[root@harbor ~]# vi /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.200.141 harbor.example.com

[root@harbor ~]# ping harbor.example.com
PING harbor.example.com (192.168.200.141) 56(84) bytes of data.
64 bytes from harbor.example.com (192.168.200.141): icmp_seq=1 ttl=64 time=0.049 ms
64 bytes from harbor.example.com (192.168.200.141): icmp_seq=2 ttl=64 time=0.042 ms
^C
--- harbor.example.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 20ms
rtt min/avg/max/mdev = 0.042/0.045/0.049/0.007 ms

// 解压harbor包,查看install.sh脚本 和 xxx-compose.yml
[root@harbor ~]# cd /usr/src/
[root@harbor src]# ls
debug  harbor-offline-installer-v2.3.5.tgz  kernels
[root@harbor src]# tar xf harbor-offline-installer-v2.3.5.tgz -C /usr/local/
[root@harbor src]# cd /usr/local/harbor/
[root@harbor harbor]# ls
common.sh             harbor.yml.tmpl  LICENSE
harbor.v2.3.5.tar.gz  install.sh       prepare

// 对harbor配置文件进行修改
[root@harbor harbor]# vi harbor.yml
# Configuration file of Harbor
  
# The IP address or hostname to access admin UI and registry service.
# DO NOT use localhost or 127.0.0.1, because Harbor needs to be accessed by external clients.
hostname: harbor.example.com   //修改此处,修改为本机主机名

# http related config
http:
  # port for http, default is 80. If https enabled, this port will redirect to https port
  port: 80

# https related config
#https:    //注释此处,没有使用证书时
  # https port for harbor, default is 443
  #  port: 443  //注释此处,没有使用证书时
  # The path of cert and key files for nginx
  #  certificate: /your/certificate/path   //注释此处,没有使用证书时
  #private_key: /your/private/key/path   //注释此处,没有使用证书时

......省略n行

harbor_admin_password: Harbor12345   //web界面admin用户的密码

# Harbor DB configuration
database:
  # The password for the root user of Harbor DB. Change this before any production use.
  password: root123   // 数据库的密码
  # The maximum number of connections in the idle connection pool. If it <=0, no idle connections are retained.
  max_idle_conns: 100   //最大空闲连接
  # The maximum number of open connections to the database. If it <= 0, then there is no limit on the number of open connections.
  # Note: the default number of connections is 1024 for postgres of harbor.
  max_open_conns: 900  //最大连接数
# The default data volume
data_volume: /data    //数据挂载目录


// 执行install.sh 安装脚本,进行安装
[root@harbor harbor]# ./install.sh 

[Step 0]: checking if docker is installed ...

Note: docker version: 20.10.12

[Step 1]: checking docker-compose is installed ...

Note: docker-compose version: 1.26.2

[Step 2]: loading Harbor images ...
.......省略n行

[Step 5]: starting Harbor ...
Creating network "harbor_harbor" with the default driver
Creating harbor-log ... done
Creating harbor-portal ... done
Creating registry      ... done
Creating harbor-db     ... done
Creating registryctl   ... done
Creating redis         ... done
Creating harbor-core   ... done
Creating nginx             ... done
Creating harbor-jobservice ... done
✔ ----Harbor has been installed and started successfully.----    //到此安装成功

// 启动harbor
[root@harbor harbor]# docker-compose start
Starting log         ... done
Starting registry    ... done
Starting registryctl ... done
Starting postgresql  ... done
Starting portal      ... done
Starting redis       ... done
Starting core        ... done
Starting jobservice  ... done
Starting proxy       ... done

使用docker ps -a 查看新建的容器

[root@harbor harbor]# docker ps -a
CONTAINER ID   IMAGE                                COMMAND                  CREATED         STATUS                   PORTS                                   NAMES
284275316b01   goharbor/harbor-jobservice:v2.3.5    "/harbor/entrypoint.…"   2 minutes ago   Up 2 minutes (healthy)                                           harbor-jobservice
cb0c4603a22d   goharbor/nginx-photon:v2.3.5         "nginx -g 'daemon of…"   2 minutes ago   Up 2 minutes (healthy)   0.0.0.0:80->8080/tcp, :::80->8080/tcp   nginx
8ed5937e548a   goharbor/harbor-core:v2.3.5          "/harbor/entrypoint.…"   2 minutes ago   Up 2 minutes (healthy)                                           harbor-core
501795de1f4a   goharbor/harbor-db:v2.3.5            "/docker-entrypoint.…"   2 minutes ago   Up 2 minutes (healthy)                                           harbor-db
f0b7eaf6d883   goharbor/harbor-portal:v2.3.5        "nginx -g 'daemon of…"   2 minutes ago   Up 2 minutes (healthy)                                           harbor-portal
9513ab79fb65   goharbor/redis-photon:v2.3.5         "redis-server /etc/r…"   2 minutes ago   Up 2 minutes (healthy)                                           redis
246b97aee305   goharbor/registry-photon:v2.3.5      "/home/harbor/entryp…"   2 minutes ago   Up 2 minutes (healthy)                                           registry
ec325af742f2   goharbor/harbor-registryctl:v2.3.5   "/home/harbor/start.…"   2 minutes ago   Up 2 minutes (healthy)                                           registryctl
571bcbdc2222   goharbor/harbor-log:v2.3.5           "/bin/sh -c /usr/loc…"   2 minutes ago   Up 2 minutes (healthy)   127.0.0.1:1514->10514/tcp               harbor-log

// 端口和容器都处于正常状态
[root@harbor harbor]# ss -anlt
State Recv-Q Send-Q  Local Address:Port Peer Address:Port
LISTEN0      128           0.0.0.0:80        0.0.0.0:*   
LISTEN0      128           0.0.0.0:22        0.0.0.0:*   
LISTEN0      128         127.0.0.1:1514      0.0.0.0:*   
LISTEN0      128              [::]:80           [::]:*   
LISTEN0      128              [::]:22           [::]:*   

访问web页面(默认用户:admin 密码:Harbor12345)
在这里插入图片描述
成功登入
在这里插入图片描述

docker主机操作

上传镜像至harbor仓库
关闭防火墙

[root@docekr ~]# systemctl stop firewalld
[root@docekr ~]# vim /etc/sysconfig/selinux 
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these three values:
[root@docekr ~]# setenforce 0
[root@docekr ~]# reboot

[root@docekr ~]# getenforce 
Disabled

docker主机上安装docekr-ce

[root@docekr ~]# cd /etc/yum.repos.d/
[root@docekr ~]#  curl -o docker-ce.repo https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo
[root@docekr ~]#  sed -i 's@https://download.docker.com@https://mirrors.tuna.tsinghua.edu.cn/docker-ce@g' docker-ce.repo


安装 docker-ce 以及依赖包和工具
[root@docekr ~]# dnf -y install yum-utils device-mapper-persistent-data lvm2
[root@docekr ~]# yum -y install docker-ce --allowerasing

#安装完成后,使用 docker version 命令查看docker的版本信息
[root@docekr ~]# docker version 
Client: Docker Engine - Community
 Version:           20.10.12
 API version:       1.41
 Go version:        go1.16.12
 Git commit:        e91ed57
 Built:             Mon Dec 13 11:45:22 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true


#配置镜像加速
[root@docekr ~]# mkdir -p /etc/docker
[root@docekr ~]# vim /etc/docker/daemon.json
{
    "registry-mirrors": ["https://7z2g0ixw.mirror.aliyuncs.com"]
}
[root@docekr ~]# systemctl daemon-reload
[root@docekr ~]# systemctl enable --now  docker

使用insecure-registries参数添加http支持

[root@docker ~]# vi /etc/docker/daemon.json 
{
    "registry-mirrors": ["https://7z2g0ixw.mirror.aliyuncs.com"],
    "insecure-registries": ["harbor.example.com"]   //添加此行
}

[root@docker ~]# systemctl daemon-reload
[root@docker ~]# systemctl restart docker

// 将harbor主机域名进行映射
[root@docker ~]# vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.200.141 harbor.example.com

[[root@docker ~]# ping harbor.example.com
PING harbor.example.com (192.168.200.141) 56(84) bytes of data.
64 bytes from harbor.example.com (192.168.200.141): icmp_seq=1 ttl=64 time=0.918 ms
64 bytes from harbor.example.com (192.168.200.141): icmp_seq=2 ttl=64 time=0.430 ms
^C
--- harbor.example.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
rtt min/avg/max/mdev = 0.430/0.674/0.918/0.244 ms

拉取busybox镜像

[root@docker ~]# docker pull busybox
Using default tag: latest
latest: Pulling from library/busybox
Digest: sha256:b5cfd4befc119a590ca1a81d6bb0fa1fb19f1fbebd0397f25fae164abe1e8a6a
Status: Image is up to date for busybox:latest
docker.io/library/busybox:latest
[root@docker ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED        
busybox      latest    ffe9d497c324   8 days ago     1.24MB

将其重命名

[root@docker ~]# docker tag busybox:latest harbor.example.com/library/busybox:latest
[root@docker ~]# docker images
REPOSITORY                           TAG       IMAGE ID       CREATED        SIZE
busybox                              latest    ffe9d497c324   8 days ago     1.24MB
harbor.example.com/library/busybox   latest    ffe9d497c324   8 days ago     1.24MB

docker login 登录harbor库 (用户密码与web端一致)

[root@docker ~]# docker login harbor.example.com
Username: admin
Password: 
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

上传镜像

[root@docker ~]# docker push harbor.example.com/library/busybox
Using default tag: latest
The push refers to repository [harbor.example.com/library/busybox]
64cac9eaf0da: Pushed 
latest: digest: sha256:50e44504ea4f19f141118a8a8868e6c5bb9856efa33f2183f5ccea7ac62aacc9 size: 527

web页面查看
在这里插入图片描述
在这里插入图片描述
用户管理
新建tom用户,设置为访客,对比管理员 权限
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

用户创建完成后,将其加入项目
在这里插入图片描述

在这里插入图片描述
将其设置为访客
在这里插入图片描述
在这里插入图片描述
权限对比
在这里插入图片描述
切换tom用户
在这里插入图片描述
在这里插入图片描述
当tom以访客的身份登入时,是无法对项目进行任何操作的。
在这里插入图片描述

harbor开机自启

因为harbor的服务是由 /usr/local/harbor/中的 docker-compose.yml 配置文件和docker中的 容器 提供的所以,我们在设置开机自启时就需要在此目录中启动容器。

容器启动、停止、重启命令

[root@harbor ~]# cd /usr/local/harbor/
[root@harbor harbor]# docker-compose stop
Stopping harbor-jobservice ... done
Stopping nginx             ... done
Stopping harbor-core       ... done
Stopping harbor-db         ... done
Stopping harbor-portal     ... done
Stopping redis             ... done
Stopping registry          ... done
Stopping registryctl       ... done
Stopping harbor-log        ... done
[root@harbor harbor]# docker-compose start
Starting log         ... done
Starting registry    ... done
Starting registryctl ... done
Starting postgresql  ... done
Starting portal      ... done
Starting redis       ... done
Starting core        ... done
Starting jobservice  ... done
Starting proxy       ... done

编写一个harbor_start.sh脚本

[root@harbor harbor]# vi harbor_start.sh
#! /bin/bash

cd /usr/local/harbor
docker-compose start

// 授予执行权限
[root@harbor harbor]# chmod +x harbor_start.sh 
[root@harbor harbor]# ll
总用量 594172
drwxr-xr-x 3 root root        20 1216 19:01 common
-rw-r--r-- 1 root root      3361 1210 15:42 common.sh
-rw-r--r-- 1 root root      5996 1216 19:04 docker-compose.yml
-rwxr-xr-x 1 root root        56 1216 19:43 harbor_start.sh
-rw-r--r-- 1 root root 608376493 1210 15:42 harbor.v2.3.5.tar.gz
-rw-r--r-- 1 root root      7849 1216 19:04 harbor.yml
-rw-r--r-- 1 root root      7840 1210 15:42 harbor.yml.tmpl
-rwxr-xr-x 1 root root      2500 1210 15:42 install.sh
-rw-r--r-- 1 root root     11347 1210 15:42 LICENSE
-rwxr-xr-x 1 root root      1881 1210 15:42 prepare

将其写入rc.local 文件中

[root@harbor harbor]# vim /etc/rc.local 
#!/bin/bash
/bin/bash /usr/local/harbor/harbor_start.sh   // 添加此行
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.

touch /var/lock/subsys/local

//授予执行权限
[root@harbor harbor]# chmod +x /etc/rc.local 
[root@harbor harbor]# ll /etc/rc.local 
lrwxrwxrwx. 1 root root 13 119 2019 /etc/rc.local -> rc.d/rc.local

重启主机,验证

[root@harbor harbor]# reboot 

Last login: Thu Dec 16 18:51:17 2021 from 192.168.200.1
[root@harbor ~]# docker ps -a
CONTAINER ID   IMAGE                                COMMAND                  CREATED          STATUS                            PORTS                                   NAMES
284275316b01   goharbor/harbor-jobservice:v2.3.5    "/harbor/entrypoint.…"   42 minutes ago   Up 2 seconds (health: starting)                                           harbor-jobservice
cb0c4603a22d   goharbor/nginx-photon:v2.3.5         "nginx -g 'daemon of…"   42 minutes ago   Up 2 seconds (health: starting)   0.0.0.0:80->8080/tcp, :::80->8080/tcp   nginx
8ed5937e548a   goharbor/harbor-core:v2.3.5          "/harbor/entrypoint.…"   42 minutes ago   Up 4 seconds (health: starting)                                           harbor-core
501795de1f4a   goharbor/harbor-db:v2.3.5            "/docker-entrypoint.…"   42 minutes ago   Up 4 seconds (health: starting)                                           harbor-db
f0b7eaf6d883   goharbor/harbor-portal:v2.3.5        "nginx -g 'daemon of…"   42 minutes ago   Up 5 seconds (health: starting)                                           harbor-portal
9513ab79fb65   goharbor/redis-photon:v2.3.5         "redis-server /etc/r…"   42 minutes ago   Up 5 seconds (health: starting)                                           redis
246b97aee305   goharbor/registry-photon:v2.3.5      "/home/harbor/entryp…"   42 minutes ago   Up 4 seconds (health: starting)                                           registry
ec325af742f2   goharbor/harbor-registryctl:v2.3.5   "/home/harbor/start.…"   42 minutes ago   Up 5 seconds (health: starting)                                           registryctl
571bcbdc2222   goharbor/harbor-log:v2.3.5           "/bin/sh -c /usr/loc…"   42 minutes ago   Up 5 seconds (health: starting)   127.0.0.1:1514->10514/tcp               harbor-log

Docker Compose语法

docker compose介绍

docker compose结构:
docker compose将所管理的容器分为三层,分别是
   工程project:由一组关联的应用容器组成的一个完整业务单元,在docker-compose.yml中定义。
   服务service:一个应用的容器,实际上可以包括若干运行相同镜像的容器实例。
   容器container。
Docker Compose 运行目录下的所有文件(docker-compose.yml)组成一个工程,一个工程包含多个服务,每个服务中定义了容器运行的镜像、参数、依赖,一个服务可包括多个容器实例。

docker compose目的:负责实现Docker容器集群的快速编排

docker compose 常用命令与配置

docker-compose ps   				列出所有运行的容器
docker-compose logs 			    查看服务日志输出
docker-compose port http 8080       输出 http 服务8080端口所绑定的公共端口
docker-compose build 				构建或者重新构建服务
docker-compose start|stop eureka    启动|停止指定服务已存在的容器
docker-compose rm eureka            删除指定服务的容器 
docker-compose up                   构建、启动容器
docker-compose kill eureka          通过发送 SIGKILL 信号来停止指定服务的容器
docker-compose scale user=3 movie=3 设置指定服务运气容器的个数,以 service=num 形式指定
docker-compose run web bash         在一个服务上执行一个命令

docker-compose.yml 属性

version:指定 docker-compose.yml 文件的写法格式
services:多个容器集合
build:配置构建时,Compose 会利用它自动构建镜像,该值可以是一个路径,也可以是一个对象,用于指定 Dockerfile 参数
	build: ./dir
	或者
	build:
		context: ./dir
		dockerfile: Dockerfile
		args:
			buildno: 1
command:覆盖容器启动后默认执行的命令
	command: bundle exec thin -p 3000  #shell格式
	或者
	command: [bundle,exec,thin,-p,3000] #列表格式
dns:配置 dns 服务器,可以是一个值或列表
    dns: 8.8.8.8  #值
	或者
	dns:          #列表格式
		- 8.8.8.8
		- 9.9.9.9
environment:环境变量配置,可以用数组或字典两种方式
    environment:   #数组格式
		RACK_ENV: development
		SHOW: 'ture'
	或者
	environment:   #字典格式
		- RACK_ENV=development
		- SHOW=ture
env_file:从文件中获取环境变量,可以指定一个文件路径或路径列表,其优先级低于environment 指定的环境变量
	env_file: .env
	或者
	env_file:
		- ./common.env
expose:暴露端口,只将端口暴露给连接的服务,而不暴露给主机
	expose:
		- "3000"
		- "8000"
image:指定服务所使用的镜像
network_mode:设置网络模式

	network_mode: "bridge"
	network_mode: "host"
	network_mode: "none"
	network_mode: "service:[service name]"
	network_mode: "container:[container name/id]"
ports:对外暴露的端口定义,和 expose 对应
	ports:   # 暴露端口信息  - "宿主机端口:容器暴露端口"
	- "8763:8763"
	- "8763:8763"
links:将指定容器连接到当前连接,可以设置别名,避免ip方式导致的容器重启动态改变的无法连接情况
	links:    # 指定服务名称:别名 
		- docker-compose-eureka-server:compose-eureka
volumes:卷挂载路径
	volumes:
	  - /lib
	  - /var

docker-compose语法

1、image

指定为镜像名称或镜像ID。如果镜像不存在,Compose将尝试从互联网拉取这个镜像,例如: image: ubuntu image: orchardup/postgresql image: a4bc65fd

2、build

指定Dockerfile所在文件夹的路径。Compose将会利用他自动构建这个镜像,然后使用这个镜像。 build: ./dir

3、command

覆盖容器启动后默认执行的命令。 command: bundle exec thin -p 3000

4、links

链接到其他服务容器,使用服务名称(同时作为别名)或服务别名(SERVICE:ALIAS)都可以

links:
 - db
 - db:database
 - redis
5、external_links

链接到docker-compose.yml外部的容器,甚至并非是Compose管理的容器。参数格式和links类似。 external_links:

- redis_1
 - project_db_1:mysql
 - project_db_2:sqlserver
6、ports

暴露端口信息。 宿主机器端口:容器端口(HOST:CONTAINER)格式或者仅仅指定容器的端口(宿主机器将会随机分配端口)都可以。

ports:
 - "3306"
 - "8080:80"
 - "127.0.0.1:8090:8001"

注意:当使用 HOST:CONTAINER 格式来映射端口时,如果你使用的容器端口小于 60 你可能会得到错误得结果,因为 YAML 将会解析 xx:yy 这种数字格式为 60 进制。所以建议采用字符串格式。

7、expose

暴露端口,与posts不同的是expose只可以暴露端口而不能映射到主机,只供外部服务连接使用;仅可以指定内部端口为参数。

expose:
 - "3000"
 - "8000"
8、volumes

设置卷挂载的路径。可以设置宿主机路径:容器路径(host:container)或加上访问模式(host:container:ro)ro就是readonly的意思,只读模式。

volumes:
 - /var/lib/mysql:/var/lib/mysql
 - /configs/mysql:/etc/configs/:ro
9、volunes_from

挂载另一个服务或容器的所有数据卷。

volumes_from:
 - service_name
 - container_name
10、environment

设置环境变量。可以属于数组或字典两种格式。 如果只给定变量的名称则会自动加载它在Compose主机上的值,可以用来防止泄露不必要的数据。

environment:
 - RACK_ENV=development
 - SESSION_SECRET
11、env_file

从文件中获取环境变量,可以为单独的文件路径或列表。 如果通过docker-compose -f FILE指定了模板文件,则env_file中路径会基于模板文件路径。 如果有变量名称与environment指令冲突,则以后者为准。

env_file: .env
env_file:
 - ./common.env
 - ./apps/web.env
 - /opt/secrets.env

环境变量文件中每一行都必须有注释,支持#开头的注释行。

# common.env: Set Rails/Rack environment
RACK_ENV=development
12、extends

基于已有的服务进行服务扩展。例如我们已经有了一个webapp服务,模板文件为common.yml.

# common.yml
webapp:
build: ./webapp
environment:
\ - DEBUG=false
\ - SEND_EMAILS=false

编写一个新的 development.yml 文件,使用 common.yml 中的 webapp 服务进行扩展。 development.yml

web:
extends:
file: common.yml
service: 
  webapp:
    ports:
      \ - "8080:80"
    links:
      \ - db
    envelopment:
      - DEBUG=true
   db:
    image: mysql:5.7

后者会自动继承common.yml中的webapp服务及相关的环境变量。

13、net

设置网络模式。使用和docker client 的 --net 参数一样的值。

# 容器默认连接的网络,是所有Docker安装时都默认安装的docker0网络.
net: "bridge"
# 容器定制的网络栈.
net: "none"
# 使用另一个容器的网络配置
net: "container:[name or id]"
# 在宿主网络栈上添加一个容器,容器中的网络配置会与宿主的一样
net: "host"

Docker会为每个节点自动创建三个网络: 网络名称 作用 bridge 容器默认连接的网络,是所有Docker安装时都默认安装的docker0网络 none 容器定制的网络栈 host 在宿主网络栈上添加一个容器,容器中的网络配置会与宿主的一样 附录: 操作名称 命令 创建网络 docker network create -d bridge mynet 查看网络列表 docker network ls

14、pid

和宿主机系统共享进程命名空间,打开该选项的容器可以相互通过进程id来访问和操作。

pid: "host"
15、dns
配置DNS服务器。可以是一个值,也可以是一个列表。
dns: 8.8.8.8
dns:
 - 8.8.8.8
 - 9.9.9.9
16、cap_add,cap_drop

添加或放弃容器的Linux能力(Capability)。

cap_add:
 - ALL
cap_drop:
 - NET_ADMIN
 - SYS_ADMIN
17、dns_search

配置DNS搜索域。可以是一个值也可以是一个列表。

dns_search: example.com
dns_search:
 - domain1.example.com
 \ - domain2.example.com
working_dir, entrypoint, user, hostname, domainname, mem_limit, privileged, restart, stdin_open, tty, cpu_shares

这些都是和 docker run 支持的选项类似。

cpu_shares: 73
working_dir: /code
entrypoint: /code/entrypoint.sh
user: postgresql
hostname: foo
domainname: foo.com
mem_limit: 1000000000
privileged: true
restart: always
stdin_open: true
tty: true

注意事项: 使用compose对Docker容器进行编排管理时,需要编写docker-compose.yml文件,初次编写时,容易遇到一些比较低级的问题,导致执行docker-compose up时先解析yml文件的错误。比较常见的是yml对缩进的严格要求。

yml文件还行后的缩进,不允许使用tab键字符,只能使用空格,而空格的数量也有要求,经过实际测试,发现每一行增加一个空格用于缩进是正常的。 比如:

web:
&lt;空格&gt;build:
&lt;空格&gt;&lt;空格&gt;command:
...

否则,很容易引起各种 yaml.scanner.ScannerError:的错误提示。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值