# Deploy a Rust or Go binary

Compile in one stage, run in another. A multi-stage Dockerfile keeps the compiler out of the image, so a Rust or Go service ships as one small binary.

## Go: a static binary on Alpine

```Dockerfile
FROM golang:1.23-alpine AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app .

FROM alpine:3.21
RUN apk add --no-cache ca-certificates
COPY --from=build /out/app /app/app
ENV PORT=3000
EXPOSE 3000
CMD ["/app/app"]
```

`CGO_ENABLED=0` produces a static binary with no C library dependency, so it runs on Alpine or even `scratch`. Keep `ca-certificates` so TLS connections to Postgres and S3 work.

## Rust: a release binary on Debian slim

```Dockerfile
FROM rust:1.83-slim AS build
WORKDIR /src
COPY . .
RUN cargo build --release && cp target/release/my-app /app-bin

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=build /app-bin /app/app
ENV PORT=3000
EXPOSE 3000
CMD ["/app/app"]
```

Replace `my-app` with your binary name. Prefer rustls features in your crates so the runtime image needs no OpenSSL.

## Listen on PORT

Read `PORT` and bind to `0.0.0.0`: `"0.0.0.0:" + os.Getenv("PORT")` in Go, or `TcpListener::bind(("0.0.0.0", port))` in Rust.

## Deploy

```
npx ezhst build dockerfile set -f Dockerfile
npx ezhst deploy
```

Or start from the [Go](/languages/go) or [Rust](/languages/rust) template with `npx ezhst build dockerfile template go --apply`. Framework examples are on the [Gin](/free-gin-hosting) and [Axum](/free-axum-hosting) pages.

## Size and memory

A compiled service usually uses a few megabytes of RAM, well inside 256 MB, and its image is far below the 1 GB limit. If a build needs build-time variables, mount the appenv secret as shown in [build-time environment variables](/guides/build-time-environment-variables).

## Frequently asked questions

### Can I use a scratch image?

Yes for a static Go binary. Copy the CA certificates from the build stage too, or TLS connections fail.
