docker-compose 容器内 networks;容器间的
2021-09-20 本文已影响0人
申_9a33
docker-compose 容器内 networks;容器间的 networks 配置
1.容器内的networks
,有一个后管理程序,包括app
,postgres
,redis
;其中app
是一个golang后端程序,需要连接到postgres
和redis
;所以docker-compose.yml
是这样的
version: "3.7"
services:
app:
build: .
container_name: "admin-back"
ports:
- "10088:10088"
# links:
# - postgres
# - redis
networks:
- mqtt
- admin-back
postgres:
image: "postgres:alpine"
networks:
- admin-back
environment:
POSTGRES_DB: "gin-admin"
POSTGRES_PASSWORD: 123456
volumes:
- pgdata:/var/lib/postgresql/data
redis:
image: "redis:alpine"
networks:
- admin-back
volumes:
- rddata:/data
volumes:
pgdata:
rddata:
networks:
mqtt:
name: mqtt
admin-back:
name: admin-back
- 1.三个应用都连接在
admin-back
,所以应用app
可以通过名称postgres
,redis
连接到数据库 - 2.容器内第二种连接第二种写法
links
也是可以,使用links
时。app
可以访问postgres
,redis
,但是postgres
,redis
无法访问app
- 3.其中
app
还连接到mqtt
网络上,mqtt
用于下面容器间网络名称
2.1容器间的networks
,一个前端项目,使用nginx部署,并且后端接口代理到上面后管理程序的接口,先看yml文件
version: "3.7"
services:
web:
image: nginx:alpine
networks:
- mqtt
ports:
- "8080:8080"
volumes:
- ./conf/nginx.conf:/etc/nginx/nginx.conf
- ./conf/conf.d:/etc/nginx/conf.d
- D:\work\vue3\ginAdmin-vue3\dist:/usr/share/nginx/html
networks:
mqtt:
name: mqtt
- 1.
networks
连接到mqtt
,此时app
和web
之间是可以相互ping通的
2.2. 再看nginx 配置
server {
listen 8080;
listen [::]:8080;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://app:10088;
}
}
- 1.
/api/
开头的请求会代理到http://app:10088
上面,完成两个容器之间的通讯
3.最后可以看一下mqtt
网络的inspect
- 运行
docker network inspect mqtt
[
{
"Name": "mqtt",
"Id": "532560ff2f92af92db2303f4beb06cefbbb1a9bb52e74ea54ed29ac25ecc1e59",
"Created": "2021-09-20T12:20:22.1251704Z",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "172.29.0.0/16",
"Gateway": "172.29.0.1"
}
]
},
"Internal": false,
"Attachable": false,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {
"3aec5b9e88b524c38c91516dda6a263f434b3b8b5c3adc350dee1c113cdbbcb4": {
"Name": "nginx_web_1",
"EndpointID": "091c464b952268ffa017b6a49f0176b640ca18885f42bbef58e74d5173ec9d20",
"MacAddress": "02:42:ac:1d:00:02",
"IPv4Address": "172.29.0.2/16",
"IPv6Address": ""
},
"a0a7d81dbaafa7e949e7c64310796f36e3569e01204bd1b547ed3ab862875450": {
"Name": "admin-back",
"EndpointID": "0313dfa1bc55074d48fa3177a278f573e87516b7bedcbd7ecfc205b214b304b4",
"MacAddress": "02:42:ac:1d:00:04",
"IPv4Address": "172.29.0.4/16",
"IPv6Address": ""
}
},
"Options": {},
"Labels": {
"com.docker.compose.network": "mqtt",
"com.docker.compose.project": "nginx",
"com.docker.compose.version": "2.0.0"
}
}
]
- 可以看到
Containers
内部有nginx_web_1
和admin-back
两个连接到此网络