Dockerfile

The dockerfile packaging type (DockerfilePackaging) builds a container image from your own Dockerfile. Stacktape builds the image and uploads it to a managed ECR repository for the configured container resource. Use this mode when you need full control over system packages, multi-stage builds, or base image selection.

The packaging type has two property variants. The container workload variant (DockerfileCwImagePackagingProps) includes buildContextPath, dockerfilePath, buildArgs, command, and entryPoint. The batch job variant (DockerfileBjImagePackagingProps) shares the same properties but does not include entryPoint.

When to use

Choose dockerfile packaging when:

  • You need system-level dependencies — native libraries or tools like ffmpeg or wkhtmltopdf.
  • Your application requires a multi-stage build to keep the final image small.
  • You already have a working Dockerfile and want to reuse it as-is.
  • You need a specific base image (e.g., distroless, or a base image reachable by the build environment).
  • The buildpack type does not detect your project, or its overrides are not enough.

When NOT to use

If your service is a JavaScript or TypeScript entry file, js-bundle builds the image for you. For other languages and frameworks, buildpack detects the project and builds the image without a Dockerfile. A Dockerfile adds maintenance work: you own base image updates, layer ordering and security patching.

If you already have a built and pushed image in a registry, use prebuilt image instead — Stacktape skips the build step entirely.

Stacktape has four container packaging types, each with container-workload and batch-job property variants. Start with js-bundle or buildpack, and switch to dockerfile when you need precise control.

TypeBest for
js-bundleJavaScript and TypeScript services with one entry file
buildpackAny detected language or framework, no Dockerfile
dockerfileFull control over the build
prebuilt-imageImage already exists in a registry

Basic example

The only required packaging property is buildContextPath — the directory sent to docker build as context, relative to your Stacktape config file. The dockerfilePath property is optional; when set, it specifies the Dockerfile path relative to buildContextPath. Examples below include a resources property — this belongs to the resource configuration (e.g., WebService, BatchJob), not the packaging type. See each resource's dedicated page for supported CPU and memory values.

export default defineConfig(() => {
  const api = new WebService({
    packaging: new DockerfilePackaging({
      buildContextPath: './'
    }),
    resources: {
      cpu: 0.25,
      memory: 512
    }
  });

  return { resources: { api } };
});

A matching Dockerfile for a Node.js app:

FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
CMD ["node", "src/server.js"]

Dockerfile path

The dockerfilePath property is optional. When set, it specifies the path to your Dockerfile relative to buildContextPath. This is useful when you maintain multiple Dockerfiles (development, production, CI) in the same repository or keep Dockerfiles in a subdirectory.

export default defineConfig(() => {
  const api = new WebService({
    packaging: new DockerfilePackaging({
      buildContextPath: './',
      dockerfilePath: './docker/Dockerfile.prod'
    }),
    resources: {
      cpu: 0.5,
      memory: 1024
    }
  });

  return { resources: { api } };
});

In this example, buildContextPath is the project root (./), and the Dockerfile lives at ./docker/Dockerfile.prod relative to that root. The leading ./ is conventional path syntax; Stacktape interprets dockerfilePath relative to buildContextPath.

Build context

The buildContextPath property defines the directory sent to docker build as context. All COPY and ADD instructions in your Dockerfile resolve relative to this directory. The path itself is relative to your Stacktape config file.

A narrower build context speeds up builds because Docker transfers fewer files to the build daemon. Combine with a .dockerignore file to exclude directories that are not needed in the image.

# .dockerignore
node_modules
.git
dist
*.md

For monorepos, point buildContextPath to the service subdirectory rather than the repo root. If you need files from outside the build context (shared libraries, workspace lockfiles), restructure so they fall within the context — Docker cannot access files above the context directory.

Build arguments

Pass values into the Dockerfile at build time using buildArgs. Each entry has an argName and a value. Stacktape passes buildArgs to docker build. In Docker, matching ARG instructions can use those values during the build; if you copy an ARG into ENV, the value becomes part of the runtime environment.

export default defineConfig(() => {
  const api = new WebService({
    packaging: new DockerfilePackaging({
      buildContextPath: './',
      buildArgs: [
        { argName: 'NODE_ENV', value: 'production' },
        { argName: 'APP_VERSION', value: '2.1.0' }
      ]
    }),
    resources: {
      cpu: 0.5,
      memory: 1024
    }
  });

  return { resources: { api } };
});

In the Dockerfile, declare matching ARG instructions to receive the values:

ARG NODE_ENV=development
ARG APP_VERSION=latest

FROM node:20-alpine
ENV NODE_ENV=${NODE_ENV}
LABEL version=${APP_VERSION}
WORKDIR /app
COPY . .
RUN npm ci
CMD ["node", "src/server.js"]

The ARG instruction can provide a default value that applies when no buildArgs override is supplied. Use this pattern so the Dockerfile works standalone (with defaults) and in Stacktape (with overrides).

Do not pass secrets through buildArgs — they are visible in the image layer history. Use runtime configuration for secrets instead. See secrets for details.

Overriding CMD and ENTRYPOINT

You can override the Dockerfile's CMD and ENTRYPOINT instructions in the Stacktape config without modifying the Dockerfile itself.

  • command overrides CMD — the default arguments passed to the entry point.
  • entryPoint overrides ENTRYPOINT — the executable that runs when the container starts.
export default defineConfig(() => {
  const api = new WebService({
    packaging: new DockerfilePackaging({
      buildContextPath: './',
      entryPoint: ['/bin/sh', '-c'],
      command: ['node src/server.js']
    }),
    resources: {
      cpu: 0.5,
      memory: 1024
    }
  });

  return { resources: { api } };
});

This is useful when you use a generic base image and want to swap the start command per stage or environment without rebuilding. The container workload packaging variant includes both entryPoint and command. The batch job packaging variant supports command but does not include entryPoint.

Multi-stage builds

Multi-stage Dockerfiles separate the build environment (compilers, dev dependencies) from the runtime image. This produces smaller, more secure containers by excluding build tools from the final layer. No special Stacktape configuration is needed — multi-stage builds work with the same buildContextPath and dockerfilePath setup.

# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Production stage
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["node", "dist/server.js"]

The builder stage installs all dependencies and compiles the application. The production stage copies only the compiled output and production node_modules, keeping the final image small. For even smaller images, replace the production base with a distroless image and copy only the compiled artifacts.

Multi-stage builds are the recommended approach for production containers. The overhead of maintaining a longer Dockerfile is repaid by faster deploys and a smaller attack surface.

Docker layer caching

Docker caches each image layer and reuses it when the layer's inputs have not changed. To maximize cache hits, order your Dockerfile instructions from least-frequently-changed to most-frequently-changed:

  1. Base image and system packages (change rarely)
  2. Dependency manifests and install step (change when you add/remove packages)
  3. Application source code (changes on every commit)
FROM node:20-alpine
WORKDIR /app

# Dependencies change less often than source code
COPY package*.json ./
RUN npm ci --omit=dev

# Source code — changes frequently
COPY . .
CMD ["node", "src/server.js"]

By copying package.json and running npm ci before copying the rest of the source, Docker reuses the cached dependency layer whenever only application code changes. This is standard Dockerfile hygiene and helps whenever the build environment has a warm cache. Stacktape's dockerfile packaging controls only the Dockerfile, build context, args, command, and entry point — caching behavior depends on Docker itself.

On your machine, Stacktape builds with Docker's local build cache. In CI, where a runner usually starts without that cache, Stacktape also stores the layer cache in the stack's ECR repository and reuses it in the next CI build. --no-remote-cache turns the ECR cache off.

Using with batch jobs

The batch job variant (DockerfileBjImagePackaging) supports command but does not include entryPoint. See batch job for the full resource configuration.

export default defineConfig(() => {
  const outputBucket = new Bucket({});

  const processor = new BatchJob({
    container: {
      packaging: new DockerfilePackaging({
        buildContextPath: './job'
      })
    },
    resources: {
      cpu: 2,
      memory: 8000
    },
    connectTo: [outputBucket]
  });

  return { resources: { outputBucket, processor } };
});

Using with multi-container workloads

A multi-container workload defines multiple containers, each with its own packaging. This example uses DockerfilePackaging for both containers, each pointing to a separate build context. You can also mix packaging modes — for example, one container built from a Dockerfile and another with a prebuilt image. See multi-container workload for the full resource configuration.

export default defineConfig(() => {
  const workload = new MultiContainerWorkload({
    containers: [
      {
        name: 'api',
        packaging: new DockerfilePackaging({
          buildContextPath: './api'
        })
      },
      {
        name: 'worker',
        packaging: new DockerfilePackaging({
          buildContextPath: './worker',
          dockerfilePath: './Dockerfile.worker'
        })
      }
    ],
    resources: {
      cpu: 1,
      memory: 2048
    }
  });

  return { resources: { workload } };
});

Best practices

These are general Docker best practices that apply to any Dockerfile used with Stacktape. The Stacktape-specific properties are buildContextPath, dockerfilePath, buildArgs, command, and entryPoint — everything else is standard Dockerfile authoring.

Keep images small. Use Alpine-based or distroless base images. Multi-stage builds prevent build tools from bloating the final layer. Smaller images deploy faster and reduce ECR storage costs.

Use .dockerignore. Exclude node_modules, .git, build artifacts, and test files from the build context. This speeds up the context transfer to the Docker daemon and prevents accidental inclusion of sensitive files.

Pin base image versions. Use node:20.11-alpine instead of node:latest. Pinned versions make builds reproducible and prevent unexpected breakage from upstream updates.

Order layers by change frequency. Copy dependency manifests and install dependencies before copying application code. This lets Docker reuse the dependency layer across code-only changes. See Docker layer caching above.

Do not run as root. Add a USER instruction in the final stage to switch to a non-root user:

RUN addgroup -S app && adduser -S app -G app
USER app

Combine related RUN instructions. Each RUN creates a new image layer. Combine related commands with && to reduce layer count. Clean up package manager caches in the same RUN instruction that installs packages — otherwise the cache persists in an earlier layer even after deletion.

Dockerfile FAQ

What base images can I use?

Your Dockerfile can use the same FROM syntax as a normal Docker build — official language images (node:20-alpine, python:3.12-slim), distroless images, or any base reachable by the build environment. Note that the packaging properties expose no setting for private-registry build-time credentials. If you need Stacktape to pull an already-built image from a private registry, use prebuilt image packaging instead — it exposes repositoryCredentialsSecretArn for that purpose.

How do I pass runtime secrets to the container?

Do not use buildArgs for secrets — they are visible in image layer history. Instead, use runtime configuration for secrets so they are not baked into the image. See secrets for details on referencing secrets at runtime.

How does dockerfile differ from buildpack?

buildpack detects the language, framework and start command from your project files and builds the image without a Dockerfile. dockerfile gives you full control, but you manage base image updates, layer ordering and security patching yourself. Use buildpack for projects that follow their ecosystem's conventions. Use dockerfile when you need a specific base image, multi-stage builds or a runtime that detection does not cover.

What is the maximum container image size?

AWS ECR does not enforce a hard image size limit. However, larger images increase deploy time because more data must be pulled when a new task starts. As a general guideline, keep web-facing images small — teams often target a few hundred MB so tasks spend less time pulling layers. Batch jobs can tolerate larger images because startup latency is less critical.

How do I debug a failing Docker build?

Run docker build locally with the same build context path and Dockerfile to reproduce the error outside Stacktape. A common cause is a COPY instruction referencing a file that lives outside buildContextPath or is excluded by .dockerignore — Docker cannot access files above the context directory. During deployment, check the deployment output for the Docker build step to identify the failure.

Can I override CMD or ENTRYPOINT without modifying the Dockerfile?

Yes. Set the command property to override the Dockerfile's CMD and entryPoint to override ENTRYPOINT. This lets you change the container's start command per stage or environment without rebuilding. The batch job packaging variant supports command but not entryPoint. See Overriding CMD and ENTRYPOINT for usage.

The API reference below covers the container workload variant (DockerfileCwImagePackagingProps), used by web services, private services, worker services, and multi-container workloads. The batch job variant (DockerfileBjImagePackagingProps) shares the same properties — buildContextPath, dockerfilePath, buildArgs, and command — but does not include entryPoint.

DockerfileCwImagePackagingProps
Click a property in the tree to see its description, default value, and full type.