Skip to content

Instantly share code, notes, and snippets.

@istudyatuni
Created February 23, 2026 09:13
Show Gist options
  • Select an option

  • Save istudyatuni/32b38d7cf638a03792456341cce42d7e to your computer and use it in GitHub Desktop.

Select an option

Save istudyatuni/32b38d7cf638a03792456341cce42d7e to your computer and use it in GitHub Desktop.
Static Rust binary with Nix + optionally docker image

How to build

# static build
nix build

# static build + docker image
nix build '.#docker'
docker load -i result

Docker image contains only static binary, so it's very lightweight

# mainly inspired by https://shivjm.blog/perfect-docker-images-for-rust-with-nix/
# static toolchain inspired by https://github.com/nix-community/fenix/issues/95#issuecomment-1444255098
{
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
fenix = {
url = "github:nix-community/fenix";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs = {
self,
nixpkgs,
flake-utils,
fenix,
}:
flake-utils.lib.eachDefaultSystem (
system: let
pkgs = import nixpkgs {inherit system;};
lib = pkgs.lib;
target = pkgs.pkgsStatic.stdenv.targetPlatform.rust.rustcTargetSpec;
toolchain = with fenix.packages.${system};
combine [
stable.rustc
stable.cargo
targets."${target}".stable.rust-std
];
rustPlatform = pkgs.pkgsStatic.makeRustPlatform {
cargo = toolchain;
rustc = toolchain;
};
meta = fromTOML (builtins.readFile ./Cargo.toml);
info =
meta.package
// {
bin.name =
if lib.hasAttr "bin" meta
then (lib.elemAt meta.bin 0).name
else meta.package.name;
};
rustApp = rustPlatform.buildRustPackage {
pname = info.name;
version = info.version;
src = ./.;
cargoLock = {
lockFile = ./Cargo.lock;
# git dependencies should be specified here
outputHashes = {};
};
meta.mainProgram = info.bin.name;
};
dockerImage = pkgs.dockerTools.buildImage {
name = info.bin.name;
tag = info.version;
config = {
Entrypoint = [(lib.getExe rustApp)];
};
};
in rec {
packages = {
rust = rustApp;
docker = dockerImage;
};
defaultPackage = packages.rust;
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment