在同一个docoker-compose中定义的
service
是直接可以通信的,docker-compose在启动后会自动创建默认的default
网络用于内部通信,但是随着项目服务的增多,不可能所有的服务都定义在一个docker-compose文件中,为了便于维护,和解耦,一般根据业务类型和容器用途等,定义多个dcoker-compose文件来管理容器,比如基础环境(redis、mq服务等)定义,公共业务(注册中心,网关等)定义,普通业务服务等。而多个docker-compose
定义的service相互不可以直接通信,需要额外配置,这里记录下来,以便后续使用
以基础服务elk
中的network
为基础,在base
服务定义的容器中复用,具体的docker-compose
文件如下
- 1.elk服务
docker-compose
文件
在最后声明一个
nwtworks
网络elk
,这样运行,启动dockr-compose后会自动创建对应的网络,也可以使用docker network create ***
来创建
version: "3"
services:
elasticsearch:
image: "elasticsearch:7.1.1"
container_name: "elasticsearch"
restart: "always"
volumes:
- "elasticsearch:/usr/share/elasticsearch"
#vim /etc/sysctl.conf
#vm.max_map_count=262144
#sysctl -w vm.max_map_count=262144
#sysctl -p
environment:
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
- discovery.type=single-node
networks:
- "elk"
ports:
- "9200:9200"
- "9300:9300"
kibana:
image: "kibana:7.1.1"
container_name: "kibana"
restart: "always"
depends_on:
- elasticsearch
volumes:
- "kibana:/usr/share/kibana"
networks:
- "elk"
ports:
- "5601:5601"
cerebro:
image: "lmenezes/cerebro"
restart: "always"
container_name: "cerebro"
ports:
- "9000:9000"
networks:
elk:
volumes:
elasticsearch:
kibana:
在需要连接通信的
docker-compose
中,文件最后声明networks,主要这里的名称是elk_elk
,使用docker network ls
- 2.基础服务
docker-compose
文件
version: '3'
services:
mysql:
image: mysql:5.7.22
restart: always
privileged: true
container_name: mysql-5.7
volumes:
- ./mysql/data:/var/lib/mysql
- ./mysql/config/my.cnf:/etc/my.cnf
- ./mysql/init:/docker-entrypoint-initdb.d/
environment:
TZ: Asia/Shanghai
MYSQL_ROOT_PASSWORD: root
ports:
- '3306:3306'
redis:
image: redis:4.0
restart: always
container_name: redis
ports:
- 6379:6379
volumes:
- ./redis/data:/data
command: redis-server
sjy-api:
image: sjy-api:latest
restart: always
container_name: sjy-api
environment:
- JVM_OPTS=-XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=128m -Xms512m -Xmx1024m -Xmn256m -Xss256k -XX:SurvivorRatio=8 -XX:+UseConcMarkSweepGC
volumes:
- ./sjy/logs:/logs
- /etc/localtime:/etc/localtime
ports:
- 5050:5050
links:
- mysql
- redis
external_links:
- elasticsearch
depends_on:
- mysql
- redis
networks:
default:
external:
name: elk_elk
- 使用
docker-compose up -d --build
启动,进入容器内部检查网络情况
root@zssy-test:/opt/docker/base# docker exec -it sjy-api /bin/sh
/ # ping elasticsearch
PING elasticsearch (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.137 ms
64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.117 ms
64 bytes from 172.18.0.2: seq=2 ttl=64 time=0.110 ms
64 bytes from 172.18.0.2: seq=3 ttl=64 time=0.098 ms
64 bytes from 172.18.0.2: seq=4 ttl=64 time=0.106 ms
64 bytes from 172.18.0.2: seq=5 ttl=64 time=0.107 ms
这样就可以使用如下配置去进行容器间的访
网友评论