1

I have my db service:

...
mysql-server:
    container_name: silos-database
    init: true
    restart: always
    build:
      context: .
      dockerfile: Dockerfile-db
    environment:
      - MYSQL_ROOT_PASSWORD=${ROOT_PASSWORD}
      - MYSQL_DATABASE=${DATABASE}
      - MYSQL_USER=${USER}
      - MYSQL_PASSWORD=${USER_PASSWORD}
    ports:
      - target: 3036
        published: 3036
    networks:
      - backend-net
    volumes:
      - type: volume
        source: db_vol
        target: /var/lib/mysql
...

This is my Dockerfile

FROM mysql:latest

The init.sql file contain same tables that my database must have

...
-- users data
CREATE TABLE IF NOT EXISTS users (
  email VARCHAR(128) PRIMARY KEY,
  username VARCHAR(64) UNIQUE,
  -- password is SHA256 hashed, so 64 characters
  password CHAR(64) NOT NULL
);

CREATE TABLE IF NOT EXISTS sessions (
  email VARCHAR(128) PRIMARY KEY,
  token TEXT NOT NULL,
  expireDate BIGINT(13) NOT NULL,
  FOREIGN KEY (email) REFERENCES users(email) ON UPDATE CASCADE ON DELETE CASCADE
);
...

How can I build a service with the content of init.sql file already inside the service?

1

1 Answer 1

1

The simplest way would be to add init.sql file to Your docker image:

FROM mysql:latest
ADD init.sql /docker-entrypoint-initdb.d

If You want to provide init.sql during container start instead of build time, You can mount directory containing init.sql into container:

mysql-server:
    container_name: silos-database
    init: true
    restart: always
    build:
      context: .
      dockerfile: Dockerfile-db
    environment:
      - MYSQL_ROOT_PASSWORD=${ROOT_PASSWORD}
      - MYSQL_DATABASE=${DATABASE}
      - MYSQL_USER=${USER}
      - MYSQL_PASSWORD=${USER_PASSWORD}
    ports:
      - target: 3036
        published: 3036
    networks:
      - backend-net
    volumes:
      - type: volume
        source: db_vol
        target: /var/lib/mysql
      - /local/path/with/initsql:/docker-entrypoint-initdb.d
Sign up to request clarification or add additional context in comments.

1 Comment

This answer is correct. And it's better if you don't recreate the Docker Image. Just use the official mysql docker image and mount the sql, sql.gz or sh extension file into /docker-entrypoint-initdb.d. You can also check MySQL Docker official documentation as well (hub.docker.com/_/mysql)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.