Build Docker Image with build-args

👍

What you'll learn

  • Building docker images via servicefoundry
  • Passing --build-arg while building docker images

This is a guide to building docker images via servicefoundry. This guide assumes you are using servicefoundry library with version >= 0.9.6 (use servicefoundry --version to see version)

Project structure

To complete this guide, you are going to create the following files:

  • Dockerfile: docker file used to build an image
  • deploy.py: contains our deployment code

Your final file structure is going to look like this:

.
├── Dockerfile
└── deploy.py

📘

In the python code shown below, make sure to replace with the FQN of the workspace where you want to deploy your service.

Deployment Code

In DockerFileBuild, you can pass build_args argument to specify args to be passed to docker build --build-arg. The build_args contains key-value pairs with key as param_name and value as param_value (both key and value follow string datatype)

In the code shown below, FOO and BAR are passed as build arguments, which is equivalent to docker build --build-arg FOO=Hello --build-arg BAR=World!

from servicefoundry import Build, Service, DockerFileBuild

service = Service(
    name="my-service-1",
    image=Build(
        build_spec=DockerFileBuild(
            dockerfile_path="./Dockerfile",
            build_context_path="./",
            build_args={
                "FOO": "Hello",
                "BAR": "World!"
            },
        ),
    ),
    ports=[{"expose": False, "port": 4000}],
)

deployment = service.deploy(workspace_fqn="<your-workspace-fqn>")

DockerFile Example

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

To know more about the ARG instruction, refer to this docker documentation. The following shows a sample docker file utilizing build arguments from the above Python code:

FROM ubuntu

ARG FOO
ARG BAR

ENV FOO_ENV=$FOO
ENV BAR_ENV=$BAR

RUN echo $FOO_ENV
RUN echo $BAR_ENV