Reputation: 3218
I'm following a MongoDB + NodeJS tutorial with my app. Everything works without Docker.. and I can in fact get the app to work up until it needs to connect to MongoDB.
If my app doesn't see MongoDB, it will print out an error and halt.
Here's my files
.env
NODE_VIEWS_PATH=../
NODE_PUBLIC_PATH=../
MONGODB_URI='mongodb://127.0.0.1:27017/myappsdb'
...
Dockerfile
FROM node:carbon
# Create app directory
WORKDIR /usr/src/mahrio
COPY package*.json ./
RUN npm install
# If you are building your code for production
# RUN npm install --only=production
COPY . .
EXPOSE 6085
CMD ["npm", "start"]
docker-compose.yml
version: "2"
services:
app:
container_name: someappname
restart: always
build: .
ports:
- "6085:6085"
links:
- mongo
depends_on:
- mongo
mongo:
container_name: mongo
image: mongo
volumes:
- ./tmp:/data/db
ports:
- "27017:27017"
Upvotes: 1
Views: 486
Reputation: 51906
When using docker-compose, for a container to connect to another container it can use the service name as a hostname to connect.
In your case, the node app needs to connect to mongo:27017
rather than localhost:27017
, since localhost from the respective of the app container will refer to itself and not to your machine.
Therefore, change the mongo url to MONGODB_URI='mongodb://mongo:27017/myappsdb'
. Also make sure that you consume the env file by adding:
app:
...
env_file:
- file.env
Upvotes: 3