Setting up a Docker container for compiling Rust code

Despite a history with Linux that reaches back more than 25 years, Windows is my main desktop operating system – partly because having been in corporate environments where I was force to use it, partly because I still develop for Windows, partly because of habitude. But I still use Linux systems a lot, and so do some of my customers. So there comes a time when code that has been developed under Windows needs to be compiled into Linux binaries. So far I’ve used WSL for this purpose, but there are downsides to it. Most importantly, WSL environments can take up considerable disk space, which is always an issue for someone dealing with data that requires a lot of storage space.

This is exacerbated by the fact that I need multiple environments. My own Linux systems currently run Ubuntu 24.04, but one customer of mine has to deal with a legacy library that forces them to use Ubuntu 20.04. So I considered getting a small and cheap computer to run Proxmox in, but then realized that I could probably achieve the same goal with Docker containers, and run them on my mini PC.

With some help from Google Gemini, I created the dockerfile and docker-compose.yaml file:

# Use Ubuntu 20.04 as the base
FROM ubuntu:20.04

# Avoid prompts during package installation
ENV DEBIAN_FRONTEND=noninteractive

# 1. Install system dependencies (build-essential is required for Rust to link)
RUN apt-get update && apt-get install -y \
    build-essential \
    gcc \
    git \
    vim \
    curl \
    && rm -rf /var/lib/apt/lists/*

# 2. Install Rust via rustup
# -s -- -y tells the installer to proceed with default options non-interactively
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y

# 3. Add Rust binaries to the system PATH
# This ensures 'cargo' and 'rustc' work immediately in the shell
ENV PATH="/root/.cargo/bin:${PATH}"

# Set the working directory for your projects
WORKDIR /home/progr

# Drop into bash by default
CMD ["/bin/bash"]
services:
  build_rust:
    build: .
    container_name: int-build
    stdin_open: true
    tty: true
    volumes:
     - ../../progr:/home/progr

The volume needs to point to the proper directory on the host system.

You can then launch the container with docker compose up -d, and stop it with docker compose down.

The way it is currently set up, the container does nothing – it just waits for you to connect to it and run commands inside. This is done with

docker exec -it int-build bash

Chances are that, once you’ve set everything up, you no longer need to run stuff interactively, but just want to execute a script that runs the build(s). You can easily do this by adding the call to the script to the CMD line in the dockerfile.

Happy compiling!

Source: https://xkcd.com/303/

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert