I can't make my docker compose work.
Here's my dockerfile:
FROM node:0.12
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev
RUN mkdir /myapp
WORKDIR /myapp
ADD . /myapp
RUN npm install
My docker-compose.yml
db:
image: mongo
ports:
- 27017
web:
build: .
command: npm start
volumes:
- .:/myapp
ports:
- 3000:3000
links:
- db
environment:
PORT: 3000
And in server.js:
var MONGO_DB;
var DOCKER_DB = process.env.DB_1_PORT;
if ( DOCKER_DB ) {
MONGO_DB = DOCKER_DB.replace( "tcp", "mongodb" ) + "/dev_db";
} else {
MONGO_DB = process.env.MONGODB;
}
mongoose.connect(MONGO_DB);
as from duplicated from this repo: https://github.com/projectweekend/Node-Backend-Seed
but process.env.DB_1_PORT
is empty. How can I add it?
Thanks
Sorry @gettho.child, I accepted your answer too quickly. I thought it was working but it wasn't. I'll report here my final solution since I have been struggling quite some to achieve it.
Dockerfile
:
FROM node:0.12
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev libkrb5-dev
RUN mkdir /myapp
WORKDIR /myapp
ADD package.json /myapp/package.json
RUN npm install
ADD . /myapp
docker-compose.yml
:
db:
image: mongo
ports:
- "27017:27017"
command: "--smallfiles --logpath=/dev/null"
web:
build: .
command: node app.js
volumes:
- .:/myapp
ports:
- "3000:3000"
links:
- db
environment:
PORT: 3000 # this is optional, allows express to use process.env.PORT instead of a raw 3000
And the interesting app.js extracts:
var MONGO_DB;
var DOCKER_DB = process.env.DB_PORT;
if ( DOCKER_DB ) {
MONGO_DB = DOCKER_DB.replace( 'tcp', 'mongodb' ) + '/myapp';
} else {
MONGO_DB = process.env.MONGODB;
}
var retry = 0;
mongoose.connect(MONGO_DB);
app.listen(process.env.PORT || 3000);
Regarding the process.env.DB_PORT
I've tried many things around. If it doesn't work out-of-the-box, I suggest to console.log(process.env);
and look for mongo's IP.
The final URL should look like: mongodb://172.17.0.76:27017/myapp
Good luck, it is worth it, Docker's awesome!
EDIT:
If the above works, I now found a techno-agnostic workflow by running:
docker-compose run web /bin/bash
printenv
I hope this is not too much self promotion but I wrote a double article on the topic which may help some of the readers: https://augustin-riedinger.fr/en/resources/using-docker-as-a-development-environment-part-1/
Cheers
Make sure that mongoDB IP (and port) in your 'Server.js' file is set to 'PORT_27017_TCP_ADDR' (check port too) - can be found when running 'docker exec {web app container id} env'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With