This example shows how to build REST API using Node.js, Express.js and MySQL database and then run the application inside Container.
MYSQLDB_USER=root MYSQLDB_ROOT_PASSWORD=root MYSQLDB_LOCAL_PORT=3307 MYSQLDB_DOCKER_PORT=3306 NODE_LOCAL_PORT=6868 NODE_DOCKER_PORT=3000
version: '3.8' services: mysqldb: image: mysql:latest restart: unless-stopped env_file: ./.env environment: - MYSQL_ROOT_PASSWORD=$MYSQLDB_ROOT_PASSWORD ports: - $MYSQLDB_LOCAL_PORT:$MYSQLDB_DOCKER_PORT volumes: - db:/var/lib/mysql - ./my_dump.sql:/docker-entrypoint-initdb.d/my_dump.sql - ./user_create.sql:/docker-entrypoint-initdb.d/user_create.sql app: depends_on: - mysqldb build: context: ./backend dockerfile: Dockerfile restart: always env_file: ./.env ports: - $NODE_LOCAL_PORT:$NODE_DOCKER_PORT environment: - DB_HOST=mysqldb - DB_USER=$MYSQLDB_USER - DB_PASSWORD=$MYSQLDB_ROOT_PASSWORD - DB_PORT=$MYSQLDB_DOCKER_PORT volumes: - ./backend:/backend stdin_open: true tty: true volumes: db:Note:
CREATE USER 'myadmin'@'%' IDENTIFIED BY 'adminpass'; GRANT ALL ON *.* TO 'myadmin'@'%'; CREATE USER 'netuser'@'localhost' IDENTIFIED BY 'netpass'; GRANT ALL ON netdb.* TO 'netuser'@'localhost';
"mysql://netsuser:netpass@mysqldb/netdb"And when I connect from my host to the database, I will use port 3307 and user myadmin. I am using port 3307, so that I can also run MySQL in my host, even if the Docker-MySQL is running.
backend/node_modules/
FROM node:19 WORKDIR /backend COPY package.json . RUN npm install COPY . . CMD npm start
If you want to use nodemon inside Container, you can use this code in Dockerfile
FROM node:19 WORKDIR /backend COPY package.json . RUN npm install -g nodemon RUN npm install COPY . . CMD npm startAnd this section in package.json
"scripts": { "start": "nodemon --legacy-watch ./bin/www", "docker": "docker-compose up --build" },