Hello World 的应用
通常,你需要创建一堆服务来形成复制和协调的应用程序。
典型的现代 Web 应用程序由数据库,api,前端和反向代理组成。
坚持
数据库需要持久性,因此我们需要一些在 swarm 中的所有节点之间共享的文件系统。它可以是 NAS,NFS 服务器,GFS2 或其他任何东西。设置它超出了范围。目前,Docker 不包含并且不管理群集中的持久性。此示例假定在所有节点上安装了/nfs/共享位置。
网络
为了能够相互通信,群中的服务需要在同一网络上。
选择 IP 范围(此处为 10.0.9.0/24)和网络名称(hello-network)并运行命令:
docker network create \
  --driver overlay \
  --subnet 10.0.9.0/24 \
  --opt encrypted \
  hello-network
数据库
我们需要的第一项服务是数据库。我们以 postgresql 为例。在 nfs/postgres 中为数据库创建一个文件夹并运行:
docker service create --replicas 1 --name hello-db \
       --network hello-network -e PGDATA=/var/lib/postgresql/data \
       --mount type=bind,src=/nfs/postgres,dst=/var/lib/postgresql/data \
       kiasaki/alpine-postgres:9.5
请注意,我们使用了 --network hello-network 和 --mount 选项。
API
创建 API 超出了这个例子的范围,所以让我们假装你在 username/hello-api 下有一个 API 镜像。
docker service create --replicas 1 --name hello-api \
       --network hello-network \
       -e NODE_ENV=production -e PORT=80 -e POSTGRESQL_HOST=hello-db \
       username/hello-api
请注意,我们传递了数据库服务的名称。Docker swarm 有一个嵌入式循环 DNS 服务器,因此 API 可以使用其 DNS 名称连接到数据库。
反向代理
让我们创建 nginx 服务,为外部世界提供 API。在共享位置创建 nginx 配置文件并运行:
docker service create --replicas 1 --name hello-load-balancer \
       --network hello-network \
       --mount type=bind,src=/nfs/nginx/nginx.conf,dst=/etc/nginx/nginx.conf \
       -p 80:80 \
       nginx:1.10-alpine
请注意,我们已使用 -p 选项发布端口。该端口可供群集中的任何节点使用。