我有问题连接我的应用程序,它作为Docker容器运行到MongoDB。我知道“links”已经被弃用了新版本的docker-compose,所以我尝试使用自定义网络。我的docker-compose.yml:
version: "3.3"
services:
app:
container_name: app
build: ./app
depends_on:
- "mongodb"
networks:
- my-network
command: pm2-docker start pm2.config.js --watch
volumes:
- ./app/logs:/opt/app/logs
- ./app:/opt/app
ports:
- "3010:80"
mongodb:
image: mongo
container_name: mongodb
restart: always
environment:
MONGO_INITDB_ROOT_PASSWORD: pw
MONGO_INITDB_ROOT_USERNAME: login
MONGO_INITDB_DATABASE: dbname
volumes:
- ./mongodb/db:/data/db
ports:
- "27017:27017"
networks:
- my-network
networks:
my-network:
driver: bridge
我的应用程序的Dockerfile:
FROM node:10.7.0
RUN npm i -g pm2
RUN pm2 install pm2-logrotate \
&& pm2 set pm2-logrotate:max_size 50M \
&& pm2 set pm2-logrotate:compress true \
&& pm2 set pm2-logrotate:workerInterval 60
RUN mkdir -p /tmp
COPY package*.json /tmp/
RUN cd /tmp \
&& npm i \
&& npm cache clean --force
RUN mkdir -p /opt/app && cp -a /tmp/node_modules /opt/app/
WORKDIR /opt/app
COPY . /opt/app/
VOLUME [ "/opt/app/logs/" ]
ENV PORT 80
ENV MONGODB_AUTH mongodb://login:pw@127.0.0.1:27017/dbname
EXPOSE 80
CMD [ "pm2-docker", "start", "pm2.config.js", "--env", "production" ]
当我运行
MongoClient.connect(process.env.MONGODB_AUTH, { useNewUrlParser: true });
时,我的应用程序会出现以下错误消息:我不明白我做错了什么。这是MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
docker network ls
的控制台输出:NETWORK ID NAME DRIVER SCOPE
4731ec3d6886 bridge bridge local
e5a6bf78bd5f docker_gwbridge bridge local
aae21167a37a host host local
d6ba0dfe01a3 myproject_default bridge local
34af02bd434d myproject_my-network bridge local
5911111233bf none null local
这是运行
docker network inspect myproject_my-network
的输出结果:[
{
"Name": "myproject_my-network",
"Id": "34af02bd434d7fe8b6755f584b45eeb0a47fafb087d7f44023598d6ae8bb79a4",
"Created": "2018-08-05T22:21:06.938675177+03:00",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "172.20.0.0/16",
"Gateway": "172.20.0.1"
}
]
},
"Internal": false,
"Attachable": true,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {},
"Options": {},
"Labels": {
"com.docker.compose.network": "my-network",
"com.docker.compose.project": "myproject"
}
}
]
当我尝试使用172.20.0.1而不是127.0.0.1时,出现了相同的错误。希望能得到有关我的问题的任何帮助。