Skip to content

Instantly share code, notes, and snippets.

@programmerq
Last active June 22, 2022 18:21
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save programmerq/7a57bc7544cddffb0fed to your computer and use it in GitHub Desktop.
Save programmerq/7a57bc7544cddffb0fed to your computer and use it in GitHub Desktop.
Simplest docker container

Step 1:

Create a statically linked executable.

(I happened to do it in a docker container. You could use any method to create a statically linked executable, really)

Source:

// hello.c
#include <stdio.h>

int main() {
    printf("Hello, world!\n");
    return 0;
}

Dockerfile

// Dockerfile
FROM debian
RUN apt-get update
RUN apt-get -y install gcc
ADD hello.c /hello.c
RUN gcc -static -o /hello hello.c

extract the statically linked binary:

mkdir fs
docker build -t build-hello .
docker run build-hello cat /hello > fs/hello
chmod +x fs/hello

Step 2

Package up the filesystem image and import it into docker:

$ ls fs
hello
$ tar -C fs -cvf hello.tar hello
a hello
$ docker import - hello < hello.tar
ead663cd606d8bd128657f1060dd0334d1631ab129b3e877dbe5d7f14a577ca1

Step 3

Run the image:

$ docker run hello /hello
Hello, world!
# Accomplishes the same thing as above, but in a single 'docker build' command thangs to multistage builds.
FROM debian
RUN apt-get update
RUN apt-get -y install gcc
ADD hello.c /hello.c
RUN gcc -static -o /hello hello.c
FROM scratch
COPY --from=0 /hello /hello
CMD ["/hello"]
@techieshark
Copy link

For anyone wanting to use alpine (tiny linux distro), here's that Dockerfile.multistage modded to do so:

# Accomplishes the same thing as above, but in a single 'docker build' command thangs to multistage builds.

FROM alpine:latest
RUN apk add --update gcc libc-dev
ADD hello.c /hello.c
RUN gcc -static -o /hello hello.c

FROM scratch
COPY --from=0 /hello /hello
CMD ["/hello"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment