Home > Software design >  express/Node testing calls to mysql from local vs docker container
express/Node testing calls to mysql from local vs docker container

Time:07-17

I am trying to make day-to-day development easier by being able to run my code on my local directly and then deploying to a container and then testing it via container. I am using a simple Express/NodeJS application that connects to a local mysql instance using both a local run directly using node and docker run via container

Local

When I create this config to connect to MYSQL via my local I am able to connect just fine (using localhost as a host)

const connection = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'user',
    password: 'user-password'
});

Using node server.js

Local using Docker

When I create this config to connect to MYSQL via my local I am able to connect just fine (my-db is the mysql service name in my docker-compose.yml since i cannot use localhost.

const connection = mysql.createConnection({
    host: 'my-db',
    port: 3306,
    user: 'user',
    password: 'user-password'
});

Using docker-compose run <myimage>

The Problem

I have to constantly keep changing my connection code to switch between localhost and my-db when running locally against node server vs running via docker-compose run . Is there a way I can make the connection agnostic of how I am running the server?

CodePudding user response:

This is a good use for an environment variable. A setup I find works well is to make host names like this configurable via environment variables, falling back to defaults that will make sense for developers who may not have them set.

const connection = mysql.createConnection({
    host: process.env.MYSQL_HOST || 'localhost',
    port: process.env.MYSQL_PORT || 3306,
    ...
});

If you just npm run start your application without setting those environment variables, you'll get those defaults. But in a Docker setup, it's easy to specify them; for example in Compose

version: '3.8'
services:
  database:
    image: mysql:8
  application:
    build: .
    environment:
      - MYSQL_HOST=database

This setup also helps you out if you're going to deploy to a production environment where your database is running on a separate host with its own backup strategy, or a cloud-hosted database like Amazon RDS; you can just set $MYSQL_HOST to point at the database host name, without changing your code.

  • Related