Assuming your node.js application connecting to mysql database to give api result
create Dockerfile as
FROM node:20
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
EXPOSE 3000/tcp
CMD [ "npm", "start" ]
create .dockerignore as
node_modules
npm-debug.log
create docker-compose.yaml as
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
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
Here my .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
and testdump.sql file contain table defination
CREATE TABLE `User` (
`id` int NOT NULL AUTO_INCREMENT,
`firstName` varchar(255) DEFAULT NULL,
`lastName` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE = InnoDB
in my node.js code i connect to mysql on mysql.example.com with port 3306
In mysql container 3306 is exposed to host machine as 3308 so on host machine following will work
mysql -h 127.0.0.1 -P 3308 -u root -p AppDb
My code is in github https://github.com/gitsangramdesai/node-mysql-docker
No comments:
Post a Comment