After sharing my environment for a node and mongo application, I want to share a less frequent configuration: Node with mysql. Quite rare with a javascript/node stack, but it happens.
Here’s my docker-compose.yml
:
version: "3.1"
services:
api:
container_name: nuovecodeApi
image: node:11
restart: always
volumes:
- ./src:/var/www/src
- ./node_modules:/var/www/node_modules
- ./package.json:/var/www/package.json
- ./nodemon.json:/var/www/nodemon.json
- ./tsconfig.json:/var/www/tsconfig.json
build: .
ports:
- "8080:8080"
depends_on:
- mysql
mysql:
image: mysql:5.7
command: --init-file /data/application/setup.sql
volumes:
- ./setup.sql:/data/application/setup.sql
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: nuovecodeDb
ports:
- "3306:3306"
As you can see I used Mysql5 instead of the most recent one that gives an autentication error during connection. This is because caching_sha2_password is introduced in MySQL 8.0, but the Node.js version is not implemented yet. According to this Stack Overflow thread there are two ways to avoid the problem without downgrading:
- Tell MySQL Server to use the legacy authentication plugin, adding
command: --default-authentication-plugin=mysql_native_password
- Use a connector .
Note the command
command: --init-file /data/application/setup.sql
This is to initialize the mysql script which creates the necessary tables for the application. It must also be mounted as a volume.
Connect in node/express
const connection = mysql.createConnection({
host, user, password, database
});
connection.connect(( error: MysqlError) => {
if (error) throw error;
});
this.app.set('connection', connection);