Custom containers

Nitric builds applications by identifying its entrypoints, which are typically defined in the nitric.yaml file as handlers. Each entrypoint in a Nitric app is built into its own container using Docker, then deployed to a cloud container runtime such as AWS Lambda, Google CloudRun or Azure Container Apps.

The Nitric CLI decides how to build those containers based on the programming language used by the entrypoint, for example if the entrypoint is a python file it will be built using Nitric's python dockerfile template. These dockerfile templates are designed with compatibility and ease of use in mind, this makes building applications convenient but may not provide additional dependencies your code relies on the ideal optimization for your application.

If you need to customize the docker container build process to add dependencies, optimize container size or some other reason, you can create a custom dockerfile template to be used by some or all of the entrypoints (services) in your application.

Specify a dockerfile template

To use a custom dockerfile template update the handlers configuration as shown below.

nitric.yaml
name: custom-example
handlers:
  - match: services/*.ts
    type: default
    docker:
      # All entrypoints in the services directory will be built using this dockerfile
      file: ./docker/node.dockerfile
      args: {}
# Enable preview feature
preview-features:
  - dockerfile

In this example we're specifying that any handlers that match the path services/*.ts will use a custom node.dockerfile for their dockerfile template.

Create a dockerfile template

It's important to note that the custom dockerfile you create needs to act as a template. This can look a bit different to how you might have written dockerfiles in the past, since the same template file will need to be used for all handlers that match the configuration the entrypoint will use a variable which contains the handler's filename.

Here are some example dockerfiles:

FROM python:3.11-slim

ARG HANDLER

ENV HANDLER=${HANDLER}
ENV PYTHONUNBUFFERED=TRUE

RUN apt-get update -y && \
    apt-get install -y ca-certificates && \
    update-ca-certificates

RUN pip install --upgrade pip pipenv

# Copy either requirements.txt or Pipfile
COPY requirements.tx[t] Pipfil[e] Pipfile.loc[k] ./

# Guarantee lock file if we have a Pipfile and no Pipfile.lock
RUN (stat Pipfile && pipenv lock) || echo "No Pipfile found"

# Output a requirements.txt file for final module install if there is a Pipfile.lock found
RUN (stat Pipfile.lock && pipenv requirements > requirements.txt) || echo "No Pipfile.lock found"

RUN pip install --no-cache-dir -r requirements.txt

COPY . .

ENTRYPOINT python $HANDLER

Create an ignore file

Custom dockerfile templates also support co-located dockerignore files. If your custom docker template is at path ./docker/node.dockerfile you can create an ignore file at ./docker/node.dockerfile.dockerignore.