简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM