crthompson
crthompson

Reputation: 15875

Does exposing ports in a Dockerfile base image, expose them in a final image?

Here I have a Dockerfile.

Notice I am using a large base image with many libraries (~2Gb), running my build, then copying the output to a smaller image for execution. I understand this to be a common practice.

# Create a base from the .net core 2.2 debian image
FROM microsoft/dotnet:2.2-sdk AS base     #<======== Base image (debian)
WORKDIR /app
# Expose ports 80 and 443
EXPOSE 80                                 #<======== Expose ports
EXPOSE 443

FROM base AS publish
WORKDIR /app
# Copy projects and src files into build image
COPY ./src/. ./src/.
# Run publish
RUN dotnet publish ./src/Core/helloworld.Core.csproj -c Release -o /app

# Create final image                     #<========= Completely new image (alpine)
FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-alpine3.9 AS final
WORKDIR /app
# Copy app from publish
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "helloworld.Core.dll"]

Do things that I do to the base image, like expose ports, extend to the final image?

Upvotes: 5

Views: 1550

Answers (2)

Andrea
Andrea

Reputation: 335

You should declare the ports in your docker-compose.yml file. You can find reference for that here https://docs.docker.com/compose/networking/

Upvotes: 0

DannyB
DannyB

Reputation: 14826

The EXPOSE directive seems to be for documentation purposes mostly (only?).

From the documentation:

The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published

So I do not see any reason to declare this anywhere other than the final step / Dockerfile.

That said, any EXPOSE directive in a parent image - either multi-stage or not - will be reflected in the metadata of any subsequent child image.

Example:

# Dockerfile
FROM scratch AS base
EXPOSE 80

FROM base
ENV HELLO world

Then run:

$ docker build -t temp .
$ docker image inspect temp

Which will output (among other things):

"ExposedPorts": {
  "80/tcp": {}
},

Upvotes: 3

Related Questions