A 06_project/Dockerfile => 06_project/Dockerfile +17 -0
@@ 0,0 1,17 @@
+FROM node:10
+
+RUN mkdir /src
+WORKDIR /src
+
+COPY package.json package-lock.json /src/
+RUN mkdir lib/ \
+ && npm install --silent --production
+
+COPY index.js /src/
+COPY lib /src/lib/
+
+ENV NODE_ENV development
+
+EXPOSE 3000
+
+CMD ["npm", "start"]
M 06_project/docker-compose.yml => 06_project/docker-compose.yml +16 -1
@@ 1,6 1,16 @@
-version: '3.1'
+version: '3'
services:
+ todos:
+ build: .
+ ports:
+ - "3000:3000"
+ environment:
+ - DATABASE_HOST=mongo
+ depends_on:
+ - mongo
+ networks:
+ - api
mongo:
image: mongo
@@ 11,3 21,8 @@ services:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
MONGO_INITDB_DATABASE: tododb
+ networks:
+ - api
+
+networks:
+ api:
M 06_project/index.js => 06_project/index.js +32 -13
@@ 2,28 2,47 @@ const MongoClient = require("mongodb").MongoClient;
const {
MONGO_INITDB_ROOT_PASSWORD = "example",
- MONGO_INITDB_ROOT_USERNAME = "root"
+ MONGO_INITDB_ROOT_USERNAME = "root",
+ DATABASE_HOST = "localhost",
+ DATABASE_PORT = 27017
} = process.env;
const index = require("./lib/app");
const log = require("./lib/logger")();
-const url = `mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@localhost:27017`;
+const url = `mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@${DATABASE_HOST}:${DATABASE_PORT}`;
const { MONGO_INITDB_DATABASE = "tododb", TODO_PORT = 3000 } = process.env;
-MongoClient.connect(
- url,
- function(err, client) {
- if (err) {
- log.error({ err }, "Error while connecting to DB");
+const connect = () => {
+ MongoClient.connect(
+ url,
+ function(err, client) {
+ if (err) {
+ log.error({ err }, "Error while connecting to DB");
+ } else if (!client) {
+ log.error("Failed to get client, retrying...");
+ } else {
+ clearInterval(interval);
+ clearTimeout(timeout);
+
+ const db = client.db(MONGO_INITDB_DATABASE);
+
+ index(db).listen(TODO_PORT, () => {
+ log.info(`Example index listening on port ${TODO_PORT}!`);
+ });
+ }
}
+ );
+};
- const db = client.db(MONGO_INITDB_DATABASE);
+const interval = setInterval(connect, 1000);
- index(db).listen(TODO_PORT, () => {
- log.info(`Example index listening on port ${TODO_PORT}!`);
- });
- }
-);
+const timeout = setTimeout(() => {
+ clearInterval(interval);
+
+ log.error("Failed to connect to database!");
+
+ process.exit(1);
+}, 5000);