Docker, MySQL - command not found in .sh file

Viewed 10160

I just set up a Dockerfile and a docker-compose.yml. And for some reason, Docker cannot run this script. Whenever this script is run, it goes through all SQL files and migrates that file.

#!/bin/bash

DB_NAME="database_name"
DB_USER="username"
DB_PASS="password"
DB_HOST="localhost"

#get current version
GET_DATABASE_VERSION="SELECT name FROM version TOP 1"
#

echo "Getting data version"
version=$(mysql -h$DB_HOST -u$DB_USER -p$DB_PASS $DB_NAME -e "SELECT name FROM version")
#trim string to get current version name
version=${version:5}
x="./config/scripts/migration/$version"
echo $version
MIGRATION_PATH="./config/scripts/migration/*"
#get migration file for newer version
for filename in $MIGRATION_PATH -maxdepth 2
do
    if [[ -f $filename ]]; then
        if [[ "$filename" > "$x" ]] || [ "$filename" == "$x" ]; then
            echo "Running migration file: $filename"
            mysql -h$DB_HOST -u$DB_USER -p$DB_PASS $DB_NAME < $filename
        fi
    fi
done

I keep getting error messages ./config/scripts/migrate_local.sh: line 25: mysql: command not found which is this line mysql -h$DB_HOST -u$DB_USER -p$DB_PASS $DB_NAME < $filename.

How can I fix this? Here are the Dockerfile and docker-compose.yml, I'm using sudo docker-compose up --build to run.

File Dockerfile

FROM node:8
MAINTAINER Tri Nguyen "me@mydomain.com"

RUN mkdir -p /usr/src
WORKDIR /usr/src

COPY package.json /usr/src
RUN npm install
RUN npm rebuild node-sass --force
COPY . /usr/src

EXPOSE 3000 8000
CMD [ "npm", "start" ]

File docker-compose.yml

version: "2"
services:
  universe:
    build: .
    working_dir: /usr/src
    environment:
    - NODE_ENV=default
    - PORT=3000
    volumes:
    - /usr/src
    ports:
    - "3000:3000"
    - "8000:8000"
    links:
    - redis
    - mysql

  redis:
    image: redis
    volumes:
    - /data/redis:/data

  mysql:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: "root"
      MYSQL_DATABASE: "database_name"
      MYSQL_USER: "username"
      MYSQL_PASSWORD: "password"
    volumes:
    - /data/mysql:/var/lib/mysql

I use winston as my logger. However, it doesn't work whatsoever, but console.log works fine. This might be the error:

universe_1  |   errno: 'ECONNREFUSED',
universe_1  |   code: 'ECONNREFUSED',
universe_1  |   syscall: 'connect',
universe_1  |   address: '127.0.0.1',
universe_1  |   port: 3307,
universe_1  |   fatal: true
1 Answers

Your universe image does not have mysql command line tools installed. You have to install it while building the Docker image.

Try the following Dockerfile:

FROM node:8
MAINTAINER Tri Nguyen "me@mydomain.com"

RUN mkdir -p /usr/src
WORKDIR /usr/src

COPY package.json /usr/src
RUN npm install
RUN npm rebuild node-sass --force
RUN set -ex; \
    apt-get update; \
    apt-get install -y --no-install-recommends \
    mysql-client

COPY . /usr/src

EXPOSE 3000 8000
CMD [ "npm", "start" ]
Related