3
\$\begingroup\$

I'm new to docker and after much research and stufy I've created a sample application and would like it to be reviewed in case if I'm missing any corner or if there's redundant information that can be simplified.

Dockerfile

FROM node

WORKDIR /src
COPY . .
RUN npm install

CMD ["npm", "start"]

docker-compose.yml

MySQL is getting initialized through schema.sql

version: '3'

services:
  database:
    image: "mysql:5.7"
    container_name: "mysql"
    ports:
      - "6603:3306"
    volumes:
      - ./schema.sql:/docker-entrypoint-initdb.d/init.sql
    environment:
      DATABASE_HOST: database
      MYSQL_ROOT_PASSWORD: rootpass
      MYSQL_DATABASE: test
      MYSQL_USER: mysql
      MYSQL_PASSWORD: password

  service:
    build: .
    image: "node"
    container_name: "nodejs"
    ports:
      - "8080:8080"
    depends_on:
      - database
    links:
      - database
    environment:
      DATABASE_HOST: database
      MYSQL_PORT: 3306
      MYSQL_DATABASE: test
      MYSQL_USER: mysql
      MYSQL_PASSWORD: password
    restart: on-failure

index.js

It has some delay, that basically waits for the mysql to become fully alive.

setTimeout(function(){
    var mysql = require('mysql');

    var con = mysql.createConnection({
        host: process.env.DATABASE_HOST,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD,
        database: process.env.MYSQL_DATABASE
    });

    con.connect(function(err) {
        if (err) throw err;
        console.log("Database Connected!");

        var http = require('http');

        //create a server object:
        http.createServer(function (req, res) {
            res.write('Hello World!'); //write a response to the client
            res.end(); //end the response
        }).listen(8080); //the server object listens on port 8080

        console.log("Listening at 8080");
    });
}, 10 * 1000);

I had one file in docker-compose.yml which I removed assuming it's not required.

#    volumes:
#      - .:/src
\$\endgroup\$
2
\$\begingroup\$

Probably it's better to you concrete node version.

Also, you can try expressjs framework.

I have got simple example of Dockerfile here in this sub-directory of my repository. But that is without Docker Compose and connection to any database.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.