据我所知,您的逻辑是正确的,docker 旨在为单个容器运行单个服务;为了达到你的目标,你还有几件事需要照顾,如果在你的 Docker 文件中声明了 EXPOSE 4040,那还不足以让服务可以访问。在 docker-compose 文件中,您还必须声明端口,即对于 nginx,您可以通过添加让主机系统监听所有接口
...
ports:
- 80:80
...
这是第一件事,您还必须考虑您希望代理从同一节点上的容器网络以哪种方式到达“应用程序”?如果是,您可以在作曲家文件中添加:
...
depends_on:
- app
...
其中 app 是在 docker-compose 文件中声明的服务名称,像这样 nginx 能够以 app 名称访问您的应用,因此重定向将指向应用:
location /app {
proxy_pass http://app:4040;
}
如果您想通过主机网络访问“应用程序”,可能因为有一天会在另一台主机上运行,您可以在容器运行 nginx 的 hosts 文件中添加条目:
...
extra_hosts:
- "app:10.10.10.10"
- "appb:10.10.10.11"
...
等等
参考:https://docs.docker.com/compose/compose-file/
编辑 01/01/2019!!!!新年快乐!!
一个使用“巨大” docker compose 文件的示例:
version: '3'
services:
app:
build: "./app" # in case you docker file is in a app dir
image: "some image name"
restart: always
command: "command to start your app"
nginx:
build: "./nginx" # in case you docker file is in a nginx dir
image: "some image name"
restart: always
ports:
- "80:80"
- "443:443"
depends_on:
- app
在上面的示例中,nginx 可以通过“app”名称访问您的应用程序,因此重定向将指向 http://app:4040
systemctl(直接从 docker 开始 - 没有 compose)
[Unit]
Description=app dockerized service
Requires=docker.service
After=docker.service
[Service]
ExecStartPre=/usr/bin/sleep 1
ExecStartPre=/usr/bin/docker pull mariadb:10.4
ExecStart=/usr/bin/docker run --restart=always --name=app -p 4040:4040 python:3.6-alpine # or your own builded image
ExecStop=/usr/bin/docker stop app
ExecStopPost=/usr/bin/docker rm -f app
ExecReload=/usr/bin/docker restart app
[Install]
WantedBy=multi-user.target
与上面的示例一样,您可以通过系统主机上的端口 4040 访问应用程序(所有接口都在侦听端口 4040 上的连接)以提供特定接口:-p 10.10.10.10:4040:像这样的 4040 会监听地址 10.10.10.10(主机)上的 4040 端口
docker-compose 与 extra_host:
version: '3'
services:
app:
build: "./app" # in case you docker file is in a app dir
image: "some image name"
restart: always
command: "command to start your app"
nginx:
build: "./nginx" # in case you docker file is in a nginx dir
image: "some image name"
restart: always
ports:
- "80:80"
- "443:443"
extra_hosts:
- "app:10.10.10.10"
像上面例子一样,nginx定义的服务可以到达10.10.10.10的名字app
至少但不是最后扩展撰写文件的服务:
docker-compose.yml:
version: '2.1'
services:
app:
extends:
file: /path/to/app-service.yml
service: app
nginx:
extends: /path/to/nginx-service.yml
service: nginx
app-service.yml:
version: "2.1"
service:
app:
build: "./app" # in case you docker file is in a app dir
image: "some image name"
restart: always
command: "command to start your app"
nginx-service.yml
version: "2.1"
service:
nginx:
build: "./nginx" # in case you docker file is in a nginx dir
image: "some image name"
restart: always
ports:
- "80:80"
- "443:443"
extra_hosts:
- "app:10.10.10.10"
真的希望上面发布的例子足够多。