본문 바로가기

개발새발 개발자/기타

[Docker] docker-compose로 DB 연결하기

말로만 듣던 Docker를 사용할 수 있는 기회가 왔다. 그냥 설치하고 연결하면 끝일 줄 알았지만...아시죠? 원래 설치하고 환경 설정하는 게 제일 오래 걸리는거^.^

 

1. Docker 실행

서로 다른 환경을 가진 사람들끼리 협업하는 것은 여간 복잡한 일이 아니다. 같은 걸 설치해도 각자의 컴퓨터 환경에 따라 실패하는 경우가 많아 프로젝트 관리가 어렵다. 이를 위해 나온 것이 바로 docker이다. docker에 대한 자세한 내용은 이곳을 참고하자.

 

1) 설치 파일 다운로드

https://hub.docker.com

 

Docker Hub

Docker Certified:Trusted & Supported Products Certified Containers provide ISV apps available as containers. Certified Plugins for networking and volumes in containers. Certified Infrastructure delivers an optimized and validated Docker platform for enterp

hub.docker.com

위의 사이트에서 우선 설치를 완료한다.

 

2) 버전 확인

$ docker version

터미널에서 docker version을 치면 버전을 확인할 수 있다.

 

[ISSUE-1] Cannot connect to the Docker deamon at unix

$ docker version
Client: Docker Engine - Community
 Version:           18.09.1
 API version:       1.39
 Go version:        go1.10.6
 Git commit:        4c52b90
 Built:             Wed Jan  9 19:33:12 2019
 OS/Arch:           darwin/amd64
 Experimental:      false
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

맨 마지막 줄을 보니 docker를 실행하지 않아 connect할 수 없다고 뜬다. 그래서 docker를 실행해보았다.

 

[ISSUE-2] Bad response from Docker engine

$ docker version
    Client: Docker Engine - Community
     Version:           18.09.2
     API version:       1.39
     Go version:        go1.10.8
     Git commit:        6247962
     Built:             Sun Feb 10 04:12:39 2019
     OS/Arch:           darwin/amd64
     Experimental:      false
    Error response from daemon: Bad response from Docker engine

아니 근데 이번엔 bad responese 라네? 어쩜 run하는 것 조차도 이렇게 쉽게 되지 않는 걸까...^.^ 하지만 우리에겐 만능키(?) Restart가 있다!

 

$ docker version
    Client: Docker Engine - Community
     Version:           18.09.2
     API version:       1.39
     Go version:        go1.10.8
     Git commit:        6247962
     Built:             Sun Feb 10 04:12:39 2019
     OS/Arch:           darwin/amd64
     Experimental:      false
    
    Server: Docker Engine - Community
     Engine:
      Version:          18.09.2
      API version:      1.39 (minimum version 1.12)
      Go version:       go1.10.6
      Git commit:       6247962
      Built:            Sun Feb 10 04:13:06 2019
      OS/Arch:          linux/amd64
      Experimental:     false

docker를 restart 하고 다시 version을 확인하니 정상적으로 server 정보까지 불러와진다.

 

2. Docker Compose 실행

docker를 단독 사용하면 옵션을 하나하나 지정해주고 컨테이너를 관리해야하는 불편함이 있다. 그래서 만들어진 것이 docker-compose다. docker-compose.yml 파일을 만들고 정보를 지정해주면 docker가 알아서 관리해준다.

 

1) docker-compose 설치

$ curl -L "https://github.com/docker/compose/releases/download/1.9.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100   618    0   618    0     0    888      0 --:--:-- --:--:-- --:--:--   887
    100 5223k  100 5223k    0     0   483k      0  0:00:10  0:00:10 --:--:--  888k

 

2) compose 파일 실행

$ ~/DE-labtory/hatchout/server% docker-compose up

docker-compose.yml이 있는 폴더로 이동해서 명령어를 입력한다.

 

[ISSUE-1] ERROR: Version in "./docker-compose.yml" is unsupported.

$ ~/DE-labtory/hatchout/server% docker-compose up
ERROR: Version in "./docker-compose.yml" is unsupported. You might be seeing this error because you're using the wrong Compose file version. Either specify a version of "2" (or "2.0") and place your service definitions under the `services` key, or omit the `version` key and place your service definitions at the root of the file to use version 1.
For more on the Compose file format versions, see https://docs.docker.com/compose/compose-file/

아앗..! 또 에러다...! 대충 읽어보니 yml에 적용된 버전과 설치한 버전이 서로 맞지 않는 것 같다. 팀원이 만든 yml 파일이라 내용을 몰랐던 게 실수였다. 그럼 docker-compose.yml을 확인해보자.

 

version: '3.3'

services:
  db:
    image: mysql
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: ----
      MYSQL_USER: ----
      MYSQL_PASSWORD: ----
      MYSQL_DATABASE: ----
    volumes:
      - data:/var/lib/mysql
    container_name: typeorm-mysql
    ports:
      - 3306:3306
  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080
volumes:
  data:

version이 3.3이라고 설정되어 있는 걸 확인했다.

 

여기서 내 멘붕은 시작됐다. compose 설치 단계에서 내가 터미널에 입력한 버전은 1.9.0이다. compose 공식 github에 가면 2019년 6월 기준 1.24.1까지만 release 되어있다. 근데 yml 버전은 3.3이라고....?

 

$ ~/DE-labtory/hatchout/server% curl -L https://github.com/docker/compose/releases/download/1.24.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   618    0   618    0     0   1043      0 --:--:-- --:--:-- --:--:--  1042
100 8947k  100 8947k    0     0   564k      0  0:00:15  0:00:15 --:--:-- 1406k

이해할 수 없었지만 일단 제일 최신인 1.24.1 버전을 다운받아 보기로 했다.

 

$ ~/DE-labtory/hatchout/server% docker-compose up

다시 compose up!

 

$ docker-compose up
Creating network "server_default" with the default driver
Creating volume "server_data" with default driver
Pulling db (mysql:)...
latest: Pulling from library/mysql
fc7181108d40: Pull complete
787a24c80112: Pull complete
a08cb039d3cd: Pull complete
4f7d35eb5394: Pull complete
5aa21f895d95: Pull complete
a742e211b7a2: Pull complete
0163805ad937: Pull complete
87f18876c3ff: Pull complete
78082f25f167: Pull complete
0a510f055c17: Pull complete
312b0999e433: Pull complete
f864cfdc0264: Pull complete
Digest: sha256:415ac63da0ae6725d5aefc9669a1c02f39a00c574fdbc478dfd08db1e97c8f1b
Status: Downloaded newer image for mysql:latest
Pulling adminer (adminer:)...
latest: Pulling from library/adminer
e7c96db7181b: Pull complete
7270d632124c: Pull complete
13605bac8660: Pull complete
7c5ed3c35631: Pull complete
1afdd81f5e69: Pull complete
e4794886df32: Pull complete
980738d80daf: Pull complete
af668e708ed6: Pull complete
738a3291a151: Pull complete
b02aac2fdd79: Pull complete
43d26e4181eb: Pull complete
e5a90a5f0de5: Pull complete
fd3c2564ebd2: Pull complete
307ef02434ed: Pull complete
76286d0ec44f: Pull complete
dbd32b9ee9bc: Pull complete
Digest: sha256:b1e7864a64dc125fea571f9d6768860f4b6d6fcd5bf0c2ed5b09c38a3b5ce7bf
Status: Downloaded newer image for adminer:latest
Creating typeorm-mysql    ... error
Creating server_adminer_1 ...

ERROR: for typeorm-mysql  Cannot start service db: driver failed programming external connectivity on endpoint typeorm-mysql (ce547e99f5378ef4ce83fe8658f58293e7cc2aa3f13c7ff0f5acfd3db74a6d5d): Error starting userland pCreating server_adminer_1 ... done

ERROR: for db  Cannot start service db: driver failed programming external connectivity on endpoint typeorm-mysql (ce547e99f5378ef4ce83fe8658f58293e7cc2aa3f13c7ff0f5acfd3db74a6d5d): Error starting userland proxy: Bind for 0.0.0.0:3306 failed: port is already allocated
ERROR: Encountered errors while bringing up the project.

오오..뭔가 엄청난 것들이 나오면서 잘 실행되는 듯 하다. 근데 마지막에 DB 드라이버 error가 뙇!!! 이미 내가 해당 port를 사용하고 있어서 그런 것 같다.

 

[ISSUE-2] DB 연결 실패

$ ~/DE-labtory/hatchout/server% sudo lsof -i :3306
Password:
COMMAND     PID    USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
mysqld       97  _mysql   28u  IPv6 0x38ef52216ee4adf5      0t0  TCP *:mysql (LISTEN)
mysqld       97  _mysql   33u  IPv6 0x38ef52216ee4a835      0t0  TCP localhost:mysql->localhost:64775 (ESTABLISHED)
mysqld       97  _mysql   34u  IPv6 0x38ef52216ee4cab5      0t0  TCP localhost:mysql->localhost:64776 (ESTABLISHED)
MySQLWork 45606 -------   14u  IPv4 0x38ef522187a6cc7d      0t0  TCP localhost:64775->localhost:mysql (ESTABLISHED)
MySQLWork 45606 -------   15u  IPv4 0x38ef52216de7e05d      0t0  TCP localhost:64776->localhost:mysql (ESTABLISHED)

3306 포트를 누가 쓰고 있나 했더니 다른 프로젝트로 쓰고 있는 mysql과 충돌이 나는 것 같았다.

근데!!!!! 아무리 터미널에서 kill 명령어로 해당 포트를 죽여도 계속 PID를 바꾸며 살아나는 것이다.......좀비인줄.......아악 이거 뭐야 몰라 무서워 ㅠㅠ

 

그렇게 뻘짓하다가 찾아낸 대반전.

Mac 기준으로 시스템 환경설정에 들어가 맨 아래의 MySQL을 클릭한 뒤,

 

오른쪽의 Stop MySQL Server를 누르면 작동을 멈춘다. kill로 죽여도 얘가 자꾸 살려내는 것이었음!

 

터미널로 해결을 못 보던 걸 클릭 한 번으로 해결했다. 때로는 왕왕왕초보의 마인드로 돌아가 쉽게 생각하면 문제가 쉽게 풀린다 :)

 

$ ~/DE-labtory/hatchout/server% docker-compose up
server_adminer_1 is up-to-date
Recreating typeorm-mysql ... done
Attaching to server_adminer_1, typeorm-mysql
adminer_1  | PHP 7.3.6 Development Server started at Thu Jun 27 13:53:48 2019
typeorm-mysql | Initializing database
typeorm-mysql | 2019-06-27T14:05:01.116725Z 0 [Warning] [MY-011070] [Server] 'Disabling symbolic links using --skip-symbolic-links (or equivalent) is the default. Consider not using this option as it' is deprecated and will be removed in a future release.
typeorm-mysql | 2019-06-27T14:05:01.116781Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.16) initializing of server in progress as process 28
typeorm-mysql | 2019-06-27T14:05:02.810182Z 5 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
typeorm-mysql | 2019-06-27T14:05:04.028185Z 0 [System] [MY-013170] [Server] /usr/sbin/mysqld (mysqld 8.0.16) initializing of server has completed
typeorm-mysql | Database initialized
typeorm-mysql | MySQL init process in progress...
typeorm-mysql | 2019-06-27T14:05:06.226937Z 0 [Warning] [MY-011070] [Server] 'Disabling symbolic links using --skip-symbolic-links (or equivalent) is the default. Consider not using this option as it' is deprecated and will be removed in a future release.
typeorm-mysql | 2019-06-27T14:05:06.227075Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.16) starting as process 79
typeorm-mysql | 2019-06-27T14:05:06.676125Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
typeorm-mysql | 2019-06-27T14:05:06.678096Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
typeorm-mysql | 2019-06-27T14:05:06.693391Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.16'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server - GPL.
typeorm-mysql | 2019-06-27T14:05:06.792796Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock'
typeorm-mysql | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
typeorm-mysql | Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
typeorm-mysql | Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
typeorm-mysql | Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
typeorm-mysql | mysql: [Warning] Using a password on the command line interface can be insecure.
typeorm-mysql | mysql: [Warning] Using a password on the command line interface can be insecure.
typeorm-mysql | mysql: [Warning] Using a password on the command line interface can be insecure.
typeorm-mysql | mysql: [Warning] Using a password on the command line interface can be insecure.
typeorm-mysql |
typeorm-mysql | 2019-06-27T14:05:11.451275Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.16)  MySQL Community Server - GPL.
typeorm-mysql |
typeorm-mysql | MySQL init process done. Ready for start up.
typeorm-mysql |
typeorm-mysql | 2019-06-27T14:05:11.811300Z 0 [Warning] [MY-011070] [Server] 'Disabling symbolic links using --skip-symbolic-links (or equivalent) is the default. Consider not using this option as it' is deprecated and will be removed in a future release.
typeorm-mysql | 2019-06-27T14:05:11.811374Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.16) starting as process 1
typeorm-mysql | 2019-06-27T14:05:12.160499Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
typeorm-mysql | 2019-06-27T14:05:12.162934Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
typeorm-mysql | 2019-06-27T14:05:12.176968Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.16'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
typeorm-mysql | 2019-06-27T14:05:12.312903Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock' bind-address: '::' port: 33060

다시 docker-compose up을 하니 정상적으로 DB에 연결되었다.