Docker Community Forums

Share and learn in the Docker community.

Why can't I connect to my database container?

Hi, newbie here (sorry and thanks for any help),

My application build is failing because I can not connect to the db image from my web image (or is the proper terminology container here?) Which is why I have inserted a “RUN ping -c 3” command so that I can test I have an actual connection, however this also fails.

When I launch just the db_network I can ping from a simple alpine container (when placed on the same network), but this doesn’t seem to work.

CONTEXT:
docker-compose.yaml

version: '3.4'
services:
    db:
        restart: always
        image: mysql:latest
        command: --default-authentication-plugin=mysql_native_password
        ports:
            - '3306:3306'
        environment:
            MYSQL_ROOT_PASSWORD: root # TODO: Change this to something more secure on actual server!
        volumes:
            - ./db:/docker-entrypoint-initdb.d/:ro
        networks:
            - db_network
    web:
        restart: always
        build:
            context: ./web
            args:
                FLASK_CONFIGURATION: conf/deployment.conf
        secrets:
            - flask
        networks:
            - nginx_network
            - db_network
        depends_on:
            - db
    nginx:
        restart: always
        build: ./nginx
        networks:
            - nginx_network
        ports:
            - "80:80"
        depends_on:
            - web
networks:
    nginx_network:
        driver: bridge
    db_network:
        driver: bridge
secrets:
    flask:
        file: flask_secret_key.txt

web/Dockerfile

FROM python:3.7 AS builder
ENV PYTHONUNBUFFERED 1

WORKDIR /packages/
RUN pip install -U pip && pip install pipenv
COPY Pipfile.lock Pipfile /packages/
RUN bash -c 'PIPENV_VENV_IN_PROJECT=1 pipenv install'

# FROM python:3.7-slim
FROM python:3.7
ARG FLASK_CONFIGURATION
ENV PYTHONUNBUFFERED=1

RUN mkdir -p /usr/src/gridt-server
COPY --from=builder /packages/ /packages
ENV PATH="/packages/.venv/bin:${PATH}" FLASK_CONFIGURATION=${FLASK_CONFIGURATION}
WORKDIR /usr/src/gridt-server
COPY . /usr/src/gridt-server

RUN ping -c 3 db
RUN flask initdb
EXPOSE 8000
# RUN apt-get update && apt-get install -y mysql-client && mysql -h db -p root
CMD ["gunicorn", "-w", "2", "-b", ":8000", "wsgi:app"]

Hi :slight_smile:

Its because when you build the image, its “isolated” and dosnt know any other containers.
You are building an IMAGE, not a container.
So these to commands:

RUN ping -c 3 db
RUN flask initdb

Will never work, because it hasnt got any connection to other containers.

So what you could do, is create a start script, that wraps “flask initdb” and “gunicorn…”, because what you define in the CMD, is what it does at container start, where it will have connection to other containers in that network.

Ahhhhh… That is a gotcha. Thank you very much, that helps a lot.

1 Like