OCaml Dockerfile build from scratch

James - Sep 15 - - Dev Community

I'm trying to package Ocaml programs for future container deployments. Upon looking at docker hub, there is no official Ocaml base images other than ocaml/opam, which doesn't really suit my use case.

I created two versions of ocaml base images, with the goal of optimized image sizes. One base off Ubuntu and one base off Alpine Linux. (may add more base os later...)

Ubuntu version:

FROM ubuntu:20.04 AS base

FROM base AS builder

# --disable-sandboxing is needed due to bwrap: No permissions to creating new namespace error
RUN apt-get update \
    && apt-get upgrade \
    && apt-get install -y opam \
    && opam init --bare -a -y --disable-sandboxing \
    && opam update

RUN opam switch create default ocaml-base-compiler.5.2.0

RUN opam install -y dune

WORKDIR /app

COPY dune-project dune hello.ml ./

# eval $(opam config env) applies dune to PATH but it only persists in a single RUN layer
RUN eval $(opam config env) \
    && dune build hello.exe

FROM base AS runner

WORKDIR /app

COPY --from=builder /app/_build/default/hello.exe /app

CMD [ "/app/hello.exe" ]
Enter fullscreen mode Exit fullscreen mode

Alpine version:

FROM alpine:3.20 AS base

FROM base AS builder

RUN apk update && \
    apk upgrade && \
    apk add build-base opam

RUN opam init --bare -a -y --disable-sandboxing \
    && opam update

RUN opam switch create default ocaml-base-compiler.5.2.0

RUN opam install -y dune

WORKDIR /app

COPY dune-project dune hello.ml ./

# eval $(opam config env) applies dune to PATH but it only persists in a single RUN layer
RUN eval $(opam config env) \
    && dune build hello.exe

FROM base AS runner

WORKDIR /app

COPY --from=builder /app/_build/default/hello.exe /app

CMD [ "/app/hello.exe" ]
Enter fullscreen mode Exit fullscreen mode

Host environment:
cpu: apple m2
macos: 14.6.1

Image size:
alpine: 10.5 mb
ubuntu: 67.7 mb

Hope these would help anyone who wants to package Ocaml programs for container deployment.

.
Terabox Video Player