问题
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