docker-compose로 MySQL 시작

10121 단어 DockerMySQLtech
【환경】
MacBook Air (M1, 2020)
OS: MacOS Big Sur version11.6
Docker Desktop for Mac version4.5.0
docker-compose에서 MySQL을 시작합니다.

디렉토리 구조


mysql
├── .env_mysql
├── Dockerfile
├── docker-compose.yml
└── init
    └── create_table.sh
.env_mysql에서 환경 변수를 기술했습니다.
init 디렉토리는 컨테이너가 시작된 후 실행되는 셸을 포함합니다.

Dockerfile


FROM mysql:8.0
ENV LANG ja_JP.UTF-8
mysql의 8.0을 기본 Image로 설정합니다.

docker-compose.yml


version: "3.8"

services:
  db:
    container_name: db
    build:
      context: .
      dockerfile: Dockerfile
    platform: linux/x86_64
    tty: true
    ports:
      - 3306:3306
    env_file:
      - ./.env_mysql
    volumes:
      - type: volume
        source: mysql-data
        target: /var/lib/mysql
      - type: bind
        source: ./init
        target: /docker-entrypoint-initdb.d

volumes:
  mysql-data:
    name: mysql-volume
M1(Apple Silicon)의 경우 Docker가 MySQL을 처리할 때 Linux.x84_64를 지정하지 않으면 오류가 발생합니다.
env_파일(.env mysiql)의 환경 변수를 컨테이너 내에서 file을 참조하여 지정할 수 있습니다.
컨테이너를 닫아도 데이터를 삭제하지 않기 위해서, Docker의 음량과 용기의/var/lib/mysiql를 연결합니다.( docker-compose로volumes 설정 )
또한, 컨테이너의/docker entrypoint-iitdb입니다.d와 호스트의init 디렉터리를 연결하고 마운트합니다.docker-entrypoint-initdb.d 이하의'.sql''.sh''.sql.gz'확장자 파일은 용기가 시작된 후에 자동으로 실행됩니다.

.env_mysql


MYSQL_DATABASE=test_database
MYSQL_USER=test_user
MYSQL_PASSWORD=password
MYSQL_ROOT_PASSWORD=root_password
.env_mysql에서 환경 변수를 기술합니다.
MySQL의 특정 환경 변수는 컨테이너가 시작될 때 MySQL 인스턴스의 설정을 변경할 수 있습니다.(MYSQL ROOOT PASSWORD를 통해 루트 사용자의 비밀번호를 설정합니다. 참조: Docker의 MySQL 이미지를 시작할 때 전달되는 환경 변수

create_table.sh


#!/bin/sh

CMD_MYSQL="mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} ${MYSQL_DATABASE}"
$CMD_MYSQL -e "create table article (
    id int(10)  AUTO_INCREMENT NOT NULL primary key,
    title varchar(50) NOT NULL,
    body varchar(1000)
    );"
$CMD_MYSQL -e  "insert into article values (1, '記事1', '記事1です。');"
$CMD_MYSQL -e  "insert into article values (2, '記事2', '記事2です。');"
용기의/docker entrypoint-iitdb.d 디렉토리에 설치된 파일은 자동으로 실행됩니다.
${환경 변수 이름}, env파일에서 설명한 환경 변수를 읽을 수 있습니다.('sql'확장자에 환경 변수를 사용하는 방법을 몰라서 이번에 셸에 기술했습니다.)
article이라는 표를 만들고 두 개의 데이터를 삽입합니다.

시험해 보다


실제로 컨테이너를 만들어 보았다.
그 전에 chemod 명령을 사용하여 init 디렉터리 아래 파일의 접근 권한을 변경합니다.
% chmod a+x ./init/*.sh
a는'모든 권한(소유자, 단체, 기타)', x는'집행 권한'을 나타낸다.
그러면 컨테이너를 작동시켜 컨테이너 내부로 들어간다.
mysql % docker-compose up -d
mysql % docker exec -it db bash
MySQL에 대한 사용자 이름, 암호 및 데이터베이스를 지정합니다.
root@175c666d6151:/# mysql -utest_user -ppassword test_database
mysql: [Warning] Using a password on the command line interface can be insecure.
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.28 MySQL Community Server - GPL

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 
article표를 작성하여 데이터가 있는지 확인합니다.
mysql> show tables;
+-------------------------+
| Tables_in_test_database |
+-------------------------+
| article                 |
+-------------------------+
1 row in set (0.02 sec)

mysql> select * from article;
+----+---------+------------------+
| id | title   | body             |
+----+---------+------------------+
|  1 | 記事1   | 記事1です。      |
|  2 | 記事2   | 記事2です。      |
+----+---------+------------------+
1 row in set (0.01 sec)
MySQL 및/docker entrypoint-iitdb.d 디렉토리의 셸이 제대로 작동하는지 확인할 수 있습니다.

참고 자료


https://qiita.com/NagaokaKenichi/items/ae037963b33a85df33f5
https://qiita.com/nanakenashi/items/180941699dc7ba9d0922

좋은 웹페이지 즐겨찾기