Search This Blog

2023/09/07

Dockerize Express.js & Mysql App

 How to Dockerize Node.js Application







Sample .dockerfile

FROM node:20
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
EXPOSE 3000/tcp
CMD [ "npm", "start" ]


Sample docker-compose.yml

version: '3.8'

services:
mysqldb:
hostname: mysql.example.com
image: mysql
restart: always
env_file: ./.env
environment:
MYSQL_ROOT_PASSWORD: $MYSQL_PASSWORD
MYSQL_DATABASE: $MYSQL_DATABASE
ports:
- $MYSQL_LOCAL_PORT:$MYSQL_DOCKER_PORT
expose:
- $MYSQL_LOCAL_PORT
volumes:
- db-config:/etc/mysql
- db-data:/var/lib/mysql
- ./db/backup/files/:/data_backup/data
- ./db-dump/testdump.sql:/docker-entrypoint-initdb.d/0_init.sql
- ./db-dump/newdump.sql:/docker-entrypoint-initdb.d/1_init.sql
networks:
- turingmysql

app:
hostname: node.example.com
build:
context: .
dockerfile: ./Dockerfile
image: sangram/apistack
ports:
- 3001:3000
expose:
- 3001
depends_on:
- mysqldb
stdin_open: true
tty: true
networks:
- turingmysql

volumes:
db-config:
db-data:

networks:
turingmysql:
driver: bridge


.env file:

MYSQL_USER_NAME = root
MYSQL_PASSWORD = "sangram#81"
MYSQL_LOCAL_PORT = 3308
MYSQL_DOCKER_PORT = 3306
MYSQL_PORT = 3306
MYSQL_DATABASE = AppDb
MYSQL_HOST = mysql.example.com
SECRET_KEY = abcd1234

On creation of mysql container importing db dump by following line in docker-compose.yml file

- ./db-dump/testdump.sql:/docker-entrypoint-initdb.d/0_init.sql
- ./db-dump/newdump.sql:/docker-entrypoint-initdb.d/1_init.sql

Code can be found at https://github.com/gitsangramdesai/node-mysql-docker

Note MYSQL_HOST is set to mysql.example.com which host name in docker-compose.yml

To Start your Application run

docker-compose up --build -d

Node application will run on port 3001

To stop container without loosing data when it starts again latter just do

docker-compose down

To Remove all images & volumes:
docker-compose down -v --rmi all


Testing Application using CURL/CURL/POSTMAN

1) Create USER

curl --location 'localhost:3001/users/signin' \
--header 'Content-Type: application/json' \
--header 'Cookie: connect.sid=s%3A_4sMyGmpeIr1JiXUuJGRFSQZrRvDFUZm.AawKVGpumezq0zMXAU1Jl0AXc9kCIM1ypAO7%2F3V3xqQ' \
--data-raw '{
"email":"sangram2681@gmail.com",
"password":"pass@123",
"firstName":"sangram",
"lastName":"desai"
}'

2) Login
curl --location 'localhost:3001/users/login' \
--header 'Content-Type: application/json' \
--header 'Cookie: connect.sid=s%3A_4sMyGmpeIr1JiXUuJGRFSQZrRvDFUZm.AawKVGpumezq0zMXAU1Jl0AXc9kCIM1ypAO7%2F3V3xqQ' \
--data-raw '{
"email":"sangram2681@gmail.com",
"password":"pass@123"
}'

In docker-compose.yml following line are their

ports:
- $MYSQL_LOCAL_PORT:$MYSQL_DOCKER_PORT
expose:
- $MYSQL_LOCAL_PORT


difference between ports & expose is that expose allow port to be accessed throuh other
docker container in network but if it in expose then accessible to host machin also

No comments:

Post a Comment