Dockerfile 可以扩展另一个 Dockerfile 吗?

我有一个这样的 PHP Dockerfile:

FROM php:7-fpm
ENV DEBIAN_FRONTEND noninteractive


RUN apt-get update && \
apt-get install -y git libicu-dev libmagickwand-dev libmcrypt-dev libcurl3-dev jpegoptim
RUN pecl install imagick && \
docker-php-ext-enable imagick


RUN docker-php-ext-install intl
RUN docker-php-ext-install pdo_mysql
RUN docker-php-ext-install opcache
RUN docker-php-ext-install mcrypt
RUN docker-php-ext-install curl
RUN docker-php-ext-install zip

我想在第一个的基础上创建另一个 Dockerfile,但是添加了一些 PHP 扩展(用于开发目的) : Xdebug 和其他东西。

我可以创建一个“ dev”Dockerfile 来扩展我的主 Dockerfile (不需要重写它)吗?

80424 次浏览

That is exactly what your FROM php:7-fpm is doing: extending the Dockerfile from the php image (with 7-fpm tag) with the contents of your Dockerfile.

So after building an image from your Dockerfile:

docker build -t my-php-base-image .

You can extend that by creating a new Dockerfile that starts with:

FROM my-php-base-image

Using multi-stage build is definitely one part of the answer here.

docker-compose v3.4 target being the second and last.

Here is a example to have 2 containers (1 normal & 1 w/ xdebug installed) living together :

Dockerfile

FROM php:7-fpm AS php_base
ENV DEBIAN_FRONTEND noninteractive


RUN apt-get update && \
apt-get install -y git libicu-dev libmagickwand-dev libmcrypt-dev libcurl3-dev jpegoptim
RUN pecl install imagick && \
docker-php-ext-enable imagick


RUN docker-php-ext-install intl
RUN docker-php-ext-install pdo_mysql
RUN docker-php-ext-install opcache
RUN docker-php-ext-install mcrypt
RUN docker-php-ext-install curl
RUN docker-php-ext-install zip


FROM php_base AS php_test


RUN pecl install xdebug
RUN docker-php-ext-enable xdebug

docker-compose.yml

version: '3.4'


services:
php:
build:
context: ./
target: php_base


php_test:
build:
context: ./
target: php_test
  

# ...

If you don't want to tag your first Dockerfile in order to use it in a FROM instruction in your next Dockerfile, and you are using Docker 20.10+, you can also do this:

# syntax = edrevo/dockerfile-plus


INCLUDE+ Dockerfile.base


RUN whatever

The INCLUDE+ instruction gets imported by the first line in the Dockerfile. You can read more about the dockerfile-plus at https://github.com/edrevo/dockerfile-plus