source

Django가 Docker를 사용하여 MariaDB 인스턴스에 연결할 수 없습니다.

bestscript 2023. 8. 28. 21:31

Django가 Docker를 사용하여 MariaDB 인스턴스에 연결할 수 없습니다.

다음 오류가 발생합니다.(2002, "Can't connect to MySQL server on 'db' (115)")Django 관리 대시보드(또는 마이그레이션 또는 DB에 연결되는 모든 항목)를 사용하려고 할 때.

이것은 나의docker-compose.yml:

version: "3.9"

services:
    db:
        image: mariadb
        restart: always
        volumes:
            - ./data/db:/var/lib/mysql
        env_file:
            - .env
        ports:
            - 3306:3306
        healthcheck:
            test: "/usr/bin/mysql --user=test --password=test --execute \"SHOW DATABASES;\""
            interval: 3s
            timeout: 1s
            retries: 5

    web:
        build: .
        command: gunicorn -b 0.0.0.0:8000 web.wsgi
        volumes:
            - .:/usr/src/app
        ports:
            - 8000:8000
        env_file:
            - .env
        depends_on:
            db:
                condition: service_healthy

.env모두 포함MYSQL_*root 암호, 사용자, 데이터베이스 이름 및 암호와 같은 서버의 env 변수입니다.또한 사용자를 위한 환경도 포함되어 있습니다.settings.py이는 다음과 같습니다.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.getenv('DB_NAME', 'test'),
        'USER': os.getenv('DB_USER', 'test'),
        'PASSWORD': os.getenv('DB_PASSWORD', 'test'),
        'HOST': os.getenv('DB_HOST', 'localhost'),
        'PORT': 3306,
    }
}

예를 들어,DB_HOST을 설정합니다..envtodb, 즉 이미지 이름docker-compose.yml웹 앱의 bash 셸로 뛰어들면 할 수 있습니다.ping db따라서 mariadb 컨테이너(같은 네트워크에 있음)를 볼 수 있습니다.

사용하려고 할 때마다mysql하지만 db 컨테이너에는 (mysql -u root -p) 다음과 같은 오류가 나타납니다.ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)

포트 3306이 DB 컨테이너에서 노출되고, 컨테이너도 상태 점검을 대기하지만 누락된 부분이 있습니다.

mariadb 컨테이너에 대한 로그(docker-compose logs --tail="all" db):

db_1            | 2021-04-13 16:48:53+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 1:10.5.9+maria~focal started.
db_1            | 2021-04-13 16:48:53+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
db_1            | 2021-04-13 16:48:53+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 1:10.5.9+maria~focal started.
db_1            | 2021-04-13 16:48:53 0 [Note] mysqld (mysqld 10.5.9-MariaDB-1:10.5.9+maria~focal) starting as process 1 ...
db_1            | 2021-04-13 16:48:53 0 [Warning] Could not increase number of max_open_files to more than 1024 (request: 32190)
db_1            | 2021-04-13 16:48:53 0 [Warning] Changed limits: max_open_files: 1024  max_connections: 151 (was 151)  table_cache: 421 (was 2000)
db_1            | 2021-04-13 16:48:54 0 [Note] InnoDB: Uses event mutexes
db_1            | 2021-04-13 16:48:54 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
db_1            | 2021-04-13 16:48:54 0 [Note] InnoDB: Number of pools: 1
db_1            | 2021-04-13 16:48:54 0 [Note] InnoDB: Using crc32 + pclmulqdq instructions
db_1            | 2021-04-13 16:48:54 0 [Note] mysqld: O_TMPFILE is not supported on /tmp (disabling future attempts)
db_1            | 2021-04-13 16:48:54 0 [Note] InnoDB: Using Linux native AIO
db_1            | 2021-04-13 16:48:54 0 [Note] InnoDB: Initializing buffer pool, total size = 134217728, chunk size = 134217728
db_1            | 2021-04-13 16:48:54 0 [Note] InnoDB: Completed initialization of buffer pool
db_1            | 2021-04-13 16:48:54 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            | 2021-04-13 16:48:54 0 [Note] InnoDB: 128 rollback segments are active.
db_1            | 2021-04-13 16:48:54 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db_1            | 2021-04-13 16:48:54 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db_1            | 2021-04-13 16:48:54 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db_1            | 2021-04-13 16:48:54 0 [Note] InnoDB: 10.5.9 started; log sequence number 45514; transaction id 20
db_1            | 2021-04-13 16:48:54 0 [Note] Plugin 'FEEDBACK' is disabled.
db_1            | 2021-04-13 16:48:54 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db_1            | 2021-04-13 16:48:54 0 [Note] InnoDB: Buffer pool(s) load completed at 210413 16:48:54
db_1            | 2021-04-13 16:48:54 0 [Note] Server socket created on IP: '::'.
db_1            | 2021-04-13 16:48:54 0 [Warning] 'proxies_priv' entry '@% root@26b39369ed70' ignored in --skip-name-resolve mode.
db_1            | 2021-04-13 16:48:54 0 [Note] Reading of all Master_info entries succeeded
db_1            | 2021-04-13 16:48:54 0 [Note] Added new Master_info '' to hash table
db_1            | 2021-04-13 16:48:54 0 [Note] mysqld: ready for connections.
db_1            | Version: '10.5.9-MariaDB-1:10.5.9+maria~focal'  socket: '/run/mysqld/mysqld.sock'  port: 3306  mariadb.org binary distribution

그래서.. 여기서 내가 놓친게 뭐죠?모든 튜토리얼이 이렇게 생겼지만, 저에게는 효과가 없습니다.페도라 33에 모비 엔진을 사용하고 있습니다.

오류 메시지에서 알 수 있듯이,mysql명령이 소켓 파일에 연결하려고 합니다./run/mysqld/mysqld.sock그러나 Docker의 MariaDB 서버는 해당 파일을 노출하도록 구성되지 않았습니다.다음을 사용해야 합니다.-H localhost연결할 위치를 알려주는 옵션입니다.이렇게 하면 파일 시스템 소켓 대신 TCP/IP 소켓에 실제로 연결됩니다.

따라서 SELinux가 연결을 거부하는 문제가 발생했습니다. 어쨌든 모든 서비스에 이 문제를 추가하면 문제가 해결됩니다.

security_opt:
    - label=type:container_runtime_t

이것은 제 경험상 적어도 페도라 33과 34에 모비 엔진에 영향을 미칩니다.

언급URL : https://stackoverflow.com/questions/67079347/django-cant-connect-to-mariadb-instance-with-docker