How to connect to other container from Dockerfile while docker-compose build

余生长醉 提交于 2021-02-11 12:29:26

问题


I try to configure docker compose for my php project. On deploy I want to update a source code, update composer dependencies and run database migrations.

So I have a docker-compose.yml file:

version: '3.0'
services:
  php:
    build: 
      context: .
      dockerfile: php/Dockerfile
    depends_on:
      - postgres
  postgres:
    image: "postgres:13-alpine"
    restart: always
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB_NAME}

Php container builds from the next Dockerfile:


# Inatall dependensies
RUN apt-get update \
&& apt-get install -y git libicu-dev postgresql-server-dev-all zip libzip-dev postgresql-client\
&& docker-php-ext-install intl pdo pdo_pgsql zip
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# Copy source files
COPY ./app /var/www/my-site

# Update project files
WORKDIR /var/www/my-site
RUN composer install
RUN php ./yii migrate --interactive=0 # This command needs to connect to the database and fails

CMD [ "php-fpm"]

When I run docker-compose build, I have this error: could not translate host name "postgres" to address: Name or service not known.

How can I take access to database container while other is building?


回答1:


Both php and postgres need to be on same network and php can access postgres using container_name which is postgres. depends_on will make sure postgres get starts before php.

version: '3.0'
services:
  php:
    build: 
      context: .
      dockerfile: php/Dockerfile
    restart: on-failure
    depends_on:
      - postgres
    networks:
      - test-network

  postgres:
    container_name: 'postgres'
    image: "postgres:13-alpine"
    restart: always
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB_NAME}
    networks:
      - test-network

networks:
  test-network:
    driver: bridge


来源:https://stackoverflow.com/questions/62957076/how-to-connect-to-other-container-from-dockerfile-while-docker-compose-build

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!