Skip to content

Instantly share code, notes, and snippets.

@johnnybenson
Created March 10, 2022 20:39
Show Gist options
  • Save johnnybenson/1c985830566c9d64d121f0f524bd0739 to your computer and use it in GitHub Desktop.
Save johnnybenson/1c985830566c9d64d121f0f524bd0739 to your computer and use it in GitHub Desktop.
Docker + Rust + Heroku + Cargo Chef -- Small multistage build that works on Heroku with dependency caching with working SSL
################################################################################
## Rust -- Recipe
################################################################################
FROM rust:latest AS chef
RUN cargo install cargo-chef
WORKDIR /var/app
FROM chef AS planner
COPY [".", "."]
RUN cargo chef prepare --recipe-path recipe.json
################################################################################
## Rust -- Build
################################################################################
FROM chef AS builder
COPY --from=planner /var/app/recipe.json recipe.json
# Create appuser
ENV USER=myapp
ENV UID=10001
RUN adduser \
--disabled-password \
--gecos "" \
--home "/nonexistent" \
--shell "/sbin/nologin" \
--no-create-home \
--uid "${UID}" \
"${USER}"
# Build dependencies - this is the caching Docker layer!
RUN cargo chef cook --release --recipe-path recipe.json
# Build application
COPY [".", "."]
RUN cargo build --release --bin myapp
RUN strip -s /var/app/target/release/myapp
################################################################################
## Rust -- Application
################################################################################
FROM debian:bullseye-slim AS runtime
RUN apt-get update -y \
&& apt-get install -y --no-install-recommends openssl libssl-dev ca-certificates \
# Clean up
&& apt-get autoremove -y \
&& apt-get clean -y \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /var/app
# Import from builder.
COPY --from=builder /etc/passwd /etc/passwd
COPY --from=builder /etc/group /etc/group
COPY --from=builder /var/app/target/release/myapp /usr/local/bin
COPY ["./docker/conf", "/var/conf"]
RUN chmod +x /var/conf/run.sh
# Heroku SSH Support
# https://devcenter.heroku.com/articles/exec#using-with-docker
# COPY ["./docker/conf/heroku-exec.sh", "/app/.profile.d/"]
# RUN rm /bin/sh && ln -s /bin/bash /bin/sh
USER myapp:myapp
EXPOSE ${PORT:-80}
CMD /usr/local/bin/myapp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment