programing

Docker-Compose를 사용하여 MariaDB에 연결하는 동안 오류가 발생했습니다. "연결 끊김:서버가 연결을 닫았습니다."

javamemo 2023. 8. 28. 20:42
반응형

Docker-Compose를 사용하여 MariaDB에 연결하는 동안 오류가 발생했습니다. "연결 끊김:서버가 연결을 닫았습니다."

docker-compose up 명령을 사용하여 공식 MariaDB 도커 이미지를 클라이언트 측 응용 프로그램 이미지에 연결하려고 합니다. 서버에 성공적으로 연결되지만 MariaDB 데이터베이스에 연결하려고 하면 약 1분 후에 "Error: Connection lost: 서버가 연결을 닫았습니다."서버를 시작할 때 데이터베이스에 로컬로 연결하는 데 문제가 없지만 동일한 코드의 도커 이미지를 연결하려고 하면 오류가 발생합니다.

내 도커 구성.yml:

version: '3.1'
services:
  webapp:

    image: client
    ports:
      - "3306:3306"
    links: 
      - db
    depends_on:
      - db
    environment:
      DATABASE_URL: "mysql://root:root@db/yelp"
db:
  image: mariadb:latest
  restart: always
  environment:
    MYSQL_ROOT_PASSWORD: root
    MYSQL_DATABASE: yelp

adminer:
  image: adminer
  restart: always
  ports:
    - 3001:3001

도커 파일:

FROM node:10

WORKDIR /cadenza/documents/SDC/leaveReview

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3306

CMD ["npm", "start"]

mysql/MariaDB index.js 연결 파일:

var mysql = require('mysql')
var connection = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: 'root',
    database: 'yelp'
});

connection.connect((err) => {
    if (err) {
        console.log('error when connecting to db', err);
    } else {
        console.log('connected to db')
    }
});

module.exports = connection;

도커 실행 시 로그 - 구성:

    docker-compose up
Starting leavereview_db_1      ... done
Starting leavereview_adminer_1 ... done
Starting leavereview_webapp_1  ... done
Attaching to leavereview_adminer_1, leavereview_db_1, leavereview_webapp_1
adminer_1  | PHP 7.2.7 Development Server started at Tue Jul  3 02:34:03 2018
webapp_1   |
webapp_1   | > yelp-reviews@1.0.0 start /cadenza/documents/SDC/leaveReview
webapp_1   | > nodemon server/index.js
webapp_1   |
db_1       | 2018-07-03  2:34:04 0 [Note] mysqld (mysqld 10.3.7-MariaDB-1:10.3.7+maria~jessie) starting as process 1 ...
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Using Linux native AIO
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Uses event mutexes
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Compressed tables use zlib 1.2.8
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Number of pools: 1
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Using SSE2 crc32 instructions
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Initializing buffer pool, total size = 256M, instances = 1, chunk size = 128M
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Completed initialization of buffer pool
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Starting crash recovery from checkpoint LSN=1630896
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: 128 out of 128 rollback segments are active.
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Waiting for purge to start
webapp_1   | [nodemon] 1.17.5
webapp_1   | [nodemon] to restart at any time, enter `rs`
webapp_1   | [nodemon] watching: *.*
webapp_1   | [nodemon] starting `node server/index.js`
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: 10.3.7 started; log sequence number 1630905; transaction id 21
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db_1       | 2018-07-03  2:34:04 0 [Note] Plugin 'FEEDBACK' is disabled.
db_1       | 2018-07-03  2:34:04 0 [Note] Recovering after a crash using tc.log
db_1       | 2018-07-03  2:34:04 0 [Note] Starting crash recovery...
db_1       | 2018-07-03  2:34:04 0 [Note] Crash recovery finished.
db_1       | 2018-07-03  2:34:04 0 [Note] Server socket created on IP: '::'.
db_1       | 2018-07-03  2:34:04 0 [Note] InnoDB: Buffer pool(s) load completed at 180703  2:34:04
db_1       | 2018-07-03  2:34:04 0 [Warning] 'proxies_priv' entry '@% root@a1a244ac54cf' ignored in --skip-name-resolve mode.
db_1       | 2018-07-03  2:34:04 0 [Note] Reading of all Master_info entries succeded
db_1       | 2018-07-03  2:34:04 0 [Note] Added new Master_info '' to hash table
db_1       | 2018-07-03  2:34:04 0 [Note] mysqld: ready for connections.
db_1       | Version: '10.3.7-MariaDB-1:10.3.7+maria~jessie'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  mariadb.org binary distribution
webapp_1   | Listening on port  3306
webapp_1   | error when connecting to db { Error: Connection lost: The server closed the connection.
webapp_1   |     at Protocol.end (/cadenza/documents/SDC/leaveReview/node_modules/mysql/lib/protocol/Protocol.js:113:13)
webapp_1   |     at Socket.<anonymous> (/cadenza/documents/SDC/leaveReview/node_modules/mysql/lib/Connection.js:109:28)
webapp_1   |     at Socket.emit (events.js:187:15)
webapp_1   |     at endReadableNT (_stream_readable.js:1081:12)
webapp_1   |     at process._tickCallback (internal/process/next_tick.js:63:19)
webapp_1   |     --------------------
webapp_1   |     at Protocol._enqueue (/cadenza/documents/SDC/leaveReview/node_modules/mysql/lib/protocol/Protocol.js:145:48)
webapp_1   |     at Protocol.handshake (/cadenza/documents/SDC/leaveReview/node_modules/mysql/lib/protocol/Protocol.js:52:23)
webapp_1   |     at Connection.connect (/cadenza/documents/SDC/leaveReview/node_modules/mysql/lib/Connection.js:130:18)
webapp_1   |     at Object.<anonymous> (/cadenza/documents/SDC/leaveReview/database/index.js:9:12)
webapp_1   |     at Module._compile (internal/modules/cjs/loader.js:702:30)
webapp_1   |     at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
webapp_1   |     at Module.load (internal/modules/cjs/loader.js:612:32)
webapp_1   |     at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
webapp_1   |     at Function.Module._load (internal/modules/cjs/loader.js:543:3)
webapp_1   |     at Module.require (internal/modules/cjs/loader.js:650:17) fatal: true, code: 'PROTOCOL_CONNECTION_LOST' }
webapp_1   | (node:29) [DEP0096] DeprecationWarning: timers.unenroll() is deprecated. Please use clearTimeout instead.

"connected to db"를 기록해야 합니다.유휴 상태 등으로 인해 서버 연결 해제를 처리하기 위해 사람들이 제안하는 해결책도 시도해 보았지만, 애초에 데이터베이스에 연결조차 되지 않습니다.

그래서 database connection index.js 파일의 호스트를 '127.0.0.1'에서 다음과 같이 변경한 후 연결되었습니다.

var connection = mysql.createConnection({
host: 'db',
user: 'root',
password: 'root',
database: 'yelp'
});

여기서 'db'는 내 도커-dker.yml 파일에 있는 'db' 이미지를 의미합니다.

개발자가 자신의 애플리케이션을 컨테이너에 연결할 수 없다며 나에게 접근할 때, 나는 보통 이렇게 합니다.저는 그들에게 다음과 같은 설정을 제공합니다.

도커-docker.yml:

version: '3.1'
services:
  webapp:
    build: .
  db:
    image: mariadb:latest
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: yelp

도커 파일:

FROM alpine
RUN apk add -U mysql-client
COPY entry.sh .
CMD ["/bin/sh", "entry.sh"]

entry.sh :

#!/bin/sh

echo "Waiting for mysql..."
until mysqladmin ping -h"db" -P"3306" --silent
do
  echo "mysql is not ready will retry in 5..."
  sleep 5
done

echo -e "\nmysql is ready"

mysql -h"db" -P"3306" -p"root" -u"root" -e "SHOW DATABASES"

그리고 이것은 당신이 실행할 때 효과가 있습니다.docker-compose up출력은 다음과 같습니다.

Starting 51145943_db_1     ... done
Starting 51145943_webapp_1 ... done
Attaching to 51145943_webapp_1, 51145943_db_1
webapp_1  | Waiting for mysql...
webapp_1  | mysql is not ready will retry in 5...
db_1      | 2018-07-03  3:17:10 0 [Note] mysqld (mysqld 10.3.7-MariaDB-1:10.3.7+maria~jessie) starting as process 1 ...
db_1      | 2018-07-03  3:17:10 0 [Note] InnoDB: Using Linux native AIO
db_1      | 2018-07-03  3:17:10 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
db_1      | 2018-07-03  3:17:10 0 [Note] InnoDB: Uses event mutexes
db_1      | 2018-07-03  3:17:10 0 [Note] InnoDB: Compressed tables use zlib 1.2.8
db_1      | 2018-07-03  3:17:10 0 [Note] InnoDB: Number of pools: 1
db_1      | 2018-07-03  3:17:10 0 [Note] InnoDB: Using SSE2 crc32 instructions
db_1      | 2018-07-03  3:17:10 0 [Note] InnoDB: Initializing buffer pool, total size = 256M, instances = 1, chunk size = 128M
db_1      | 2018-07-03  3:17:10 0 [Note] InnoDB: Completed initialization of buffer pool
db_1      | 2018-07-03  3:17:10 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
db_1      | 2018-07-03  3:17:11 0 [Note] InnoDB: 128 out of 128 rollback segments are active.
db_1      | 2018-07-03  3:17:11 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db_1      | 2018-07-03  3:17:11 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db_1      | 2018-07-03  3:17:11 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db_1      | 2018-07-03  3:17:11 0 [Note] InnoDB: 10.3.7 started; log sequence number 1630896; transaction id 21
db_1      | 2018-07-03  3:17:11 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db_1      | 2018-07-03  3:17:11 0 [Note] Plugin 'FEEDBACK' is disabled.
db_1      | 2018-07-03  3:17:11 0 [Note] Server socket created on IP: '::'.
db_1      | 2018-07-03  3:17:11 0 [Warning] 'proxies_priv' entry '@% root@4a91686036a2' ignored in --skip-name-resolve mode.
db_1      | 2018-07-03  3:17:11 0 [Note] InnoDB: Buffer pool(s) load completed at 180703  3:17:11
db_1      | 2018-07-03  3:17:11 0 [Note] Reading of all Master_info entries succeded
db_1      | 2018-07-03  3:17:11 0 [Note] Added new Master_info '' to hash table
db_1      | 2018-07-03  3:17:11 0 [Note] mysqld: ready for connections.
db_1      | Version: '10.3.7-MariaDB-1:10.3.7+maria~jessie'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  mariadb.org binary distribution
db_1      | 2018-07-03  3:17:15 8 [Warning] Access denied for user 'root'@'172.22.0.3' (using password: NO)
webapp_1  |
webapp_1  | mysql is ready
webapp_1  | Database
webapp_1  | information_schema
webapp_1  | mysql
webapp_1  | performance_schema
webapp_1  | yelp
51145943_webapp_1 exited with code 0

이것은 컨테이너 간의 연결이 작동하고 있으며 컨테이너가 가진 문제가 응용 프로그램에 따라 다르다는 것을 증명합니다.연결 문자열을 잘못된 형식으로 전달하거나, 잘못된 서버 이름을 사용하거나, mysql이 아직 작동하지 않을 때 초기에 연결을 시도할 수 있습니다.

이를 입증한 그들은 이제 자신이나 제 설정에 작은 변화를 주면서 무언가가 깨질 때까지 더 가까이 다가설 수 있도록 "격차를 메울" 수 있습니다.그 마지막 단계에서 범인이 밝혀집니다.예를 들어, 추가할 경우mysql명령줄을 응용 프로그램 컨테이너에 연결하면 실제로 연결되지만 응용 프로그램이 연결되지 않으므로 응용 프로그램 코드에서 이유를 찾아야 합니다.

제 경험으로 볼 때, 이유가 즉시 명확하지 않을 때 이와 같은 문제를 해결하는 가장 빠른 방법입니다.

언급URL : https://stackoverflow.com/questions/51145943/error-connecting-to-mariadb-using-docker-compose-connection-lost-the-server-c

반응형