I want to use mySql DB in my project and use docker-compose for making it all work.
Here is my folder strucuture:
Here is mySql config that I’m using
import mysql from 'mysql';
import dotenv from 'dotenv';
dotenv.config();
const pool = mysql.createPool({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
connectionLimit: process.env.DB_CONNECTION_LIMIT
});
export default pool;
Thats my docker-compose file:
services:
mysqldb:
image: mysql:8.0
container_name: mysql_c
command: --default-authentication-plugin=mysql_native_password
restart: unless-stopped
volumes:
- ./backend/database/init.sql:/docker-entrypoint-initdb.d/0_init.sql
- $HOME/database:/var/lib/mysql
ports:
- 3306:3306
expose:
- 3306
environment:
MYSQL_DATABASE: usersdb
MYSQL_USER: admin
MYSQL_PASSWORD: letmein
MYSQL_ROOT_PASSWORD: letmein
SERVICE_TAGS: dev
SERVICE_NAME: mysqldb
backend:
build: ./backend
container_name: backend_c
ports:
- "3005:3005"
volumes:
- ./backend:/app
- /app/node_modules
frontend:
build: ./frontend
container_name: frontend_c
ports:
- "3000:3000"
volumes:
- ./frontend:/app
- /app/node_modules
stdin_open: true
tty: true
networks:
internalnet:
driver: bridge
and that init.sql, where I’m trying to make DB initialisation:
CREATE DATABASE IF NOT EXISTS usersdb;
USE usersdb;
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
email VARCHAR(255) NOT NULL,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
image_url VARCHAR(255) DEFAULT NULL,
phone VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
CONSTRAINT UQ_Users_Email UNIQUE (email)
);
and here is package.json file, where I’m uping docker
{
"name": "pet",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "index.js",
"scripts": {
"start": "docker compose up"
},
"keywords": [],
"author": "",
"license": "ISC"
}
the problem is that when I’m entering to the DB with this command
mysql -h localhost -P 3306 --protocol=tcp -uroot -pletmein
all works fine and its leting me in, but when I’ searching for my DB there is no usersDb that I was expecting to create.