본문 바로가기

DevOps & Infra/Docker

Docker에서 MySQL 서버 실행하기

이 문서의 내용

    MySQL 이미지 다운로드

    docker pull 명령어를 사용해 MySQL 이미지를 다운로드합니다. 태그에서 버전을 지정하지 않으면 최신 버전을 다운로드합니다.

    $ docker pull mysql
    
    Using default tag: latest
    latest: Pulling from library/mysql
    8e0176adc18c: Pull complete 
    2d2c52718f65: Pull complete 
    d88d03ce139b: Pull complete 
    4a7d7f11aa1e: Pull complete 
    ce5949193e4c: Pull complete 
    f7f024dfb329: Pull complete 
    5fc3c840facc: Pull complete 
    509068e49488: Pull complete 
    cbc847bab598: Pull complete 
    942bef62a146: Pull complete 
    Digest: sha256:1773f3c7aa9522f0014d0ad2bbdaf597ea3b1643c64c8ccc2123c64afd8b82b1
    Status: Downloaded newer image for mysql:latest
    docker.io/library/mysql:latest

    MySQL 이미지 버전을 지정하려면 태그를 입력합니다. 도커에서 사용 할 수 있는 MySQL 버전은 DockerHub에서 확인합니다.

    예를 들어 8.0.35 버전을 다운로드하려면 다음과 같이 입력합니다.

    $ docker pull mysql:8.0.35

    docker images 명령어로 다운로드한 이미지를 확인합니다.

    $ docker images
    
    REPOSITORY        TAG       IMAGE ID       CREATED         SIZE
    mysql             latest    a3b6608898d6   5 weeks ago     596MB

    MySQL 컨테이너 실행

    docker run 명령어를 사용해 MySQL 이미지를 컨테이너로 실행합니다.

    $ docker run --name <컨테이너 이름> -e MYSQL_ROOT_PASSWORD=<패스워드> -d -p 3306:3306 mysql:latest
    
    cc58c0e109650110f8c5ba75ae177ccf8cd72ba1b1c19212898a8789cc92c95d
    코드 비고
    Line 1 --name <컨테이너 이름> 컨테이너 이름을 입력합니다.
    MYSQL_ROOT_PASSWORD=<패스워드> Root 계정의 엑세스 비밀번호를 입력합니다.
    -d 컨테이너를 데몬으로 실행합니다.
    -p 3306:3306 컨테이너의 3306 포트를 호스트의 3306 포트와 매핑합니다.
    mysql:latest latest 태그의 MySQL 이미지를 실행합니다. 임의의 버전을 실행하려면 태그에서 MySQL 버전을 지정합니다.
    Line 3 cc58c0e10965... 명령어로 실행된 컨테이너 ID입니다.

    docker container ls 명령어를 사용해 실행된 컨테이너를 확인합니다.

    $ docker container ls
    
    CONTAINER ID   IMAGE             COMMAND                  CREATED          STATUS          PORTS                               NAMES
    cc58c0e10965   mysql:latest      "docker-entrypoint.s…"   47 seconds ago   Up 46 seconds   0.0.0.0:3306->3306/tcp, 33060/tcp   mysql

    MySQL 접속 확인

    docker exec -it <컨테이너 이름> /bin/bash 명령어를 사용해 컨테이너에 접속합니다.

    컨테이너 쉘에서 mysql -u root -p를 입력하고 컨테이너 실행문의 MYSQL_ROOT_PASSWORD로 지정한 Root 계정의 엑세스 비밀번호를 입력합니다.

    $ docker exec -it mysql /bin/bash
    
    bash-4.4# mysql -u root -p
    Enter password: 
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 8
    Server version: 8.2.0 MySQL Community Server - GPL
    
    Copyright (c) 2000, 2023, 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>