43

How to create two images in one Dockerfile, they only copy different files.

Shouldn't this produce two images img1 & img2, instead it produces two unnamed images d00a6fc336b3 & a88fbba7eede

Dockerfile:

FROM alpine as img1
COPY file1.txt .

FROM alpine as img2
COPY file2.txt .

Instead this is the result of docker build .

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
<none>              <none>              d00a6fc336b3        4 seconds ago       4.15 MB
<none>              <none>              a88fbba7eede        5 seconds ago       4.15 MB
alpine              latest              3fd9065eaf02        3 months ago        4.15 MB
John
  • 655
  • 2
  • 6
  • 12
  • 1
    As far as I know you can not tag an image from a Dockerfile. The `as` in your Dockerfile is for multi-stage builds, see, e.g., https://docs.docker.com/develop/develop-images/multistage-build/ – fl9 Apr 10 '18 at 13:22

2 Answers2

49

You can use a docker-compose file using the target option:

version: '3.4'
services:
  img1:
    build:
      context: .
      target: img1
  img2:
    build:
      context: .
      target: img2

using your Dockerfile with the following content:

FROM alpine as img1
COPY file1.txt .

FROM alpine as img2
COPY file2.txt .
Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
  • Can you use this in dockerhub's automated builds ? – jonenst Aug 21 '18 at 10:05
  • I know this is a quite old answer, but I am currently trying your solution and it throws a pretty undefined error at me, it says `ERROR: failed to reach build target io.klib.aries.example.x86 in Dockerfile` I am using basically the same code as you in the Dockerfile and the compose yaml. Any suggestions? – A7exSchin Apr 03 '20 at 17:18
36

You can build multiple images from one Docker file by running docker build for each build stage name want to pick out of the Dockerfile (FROM alpine as name).

By default docker builds the image from the last command in the Dockerfile, however you can target the build to an intermediate layer. Extending from the example Dockerfile in the question, one can:

docker build -t image1 --target img1 .

ref: https://docs.docker.com/engine/reference/commandline/build/#specifying-target-build-stage---target

hi2meuk
  • 581
  • 5
  • 5