gocontainersbuildah

Building a minimal container for a Go program


I want to build a tiny container image from scratch using Buildah to run a Go app. Apart from the app itself, what other libraries etc need to be included. I am thinking that glibc is needed - is there anything else?

So in summary, I think I am asking "what are all the external dependencies that a compiled Go app needs on Linux?"


Solution

  • @Dave C gave the information to correctly answer this. Using ldd with the test app returned:

    [bryon@localhost resttest]$ ldd restest
        linux-vdso.so.1 (0x00007fff139fe000)
        libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fbad6ce2000)
        libc.so.6 => /lib64/libc.so.6 (0x00007fbad691f000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fbad6f02000)
    [bryon@localhost resttest]$ 
    

    So for those looking to build a minimal container with Buildah, the BASH script to generate it would look like this:

    #!/bin/bash
    #
    # Run this shell script after you have run the command: "buildah unshare"
    #
    git clone https://github.com/bryonbaker/resttest.git
    cd resttest
    go build restest.go
    
    container=$(buildah from scratch)
    mnt=$(buildah mount $container)
    mkdir $mnt/bin
    mkdir $mnt/lib64
    buildah config --workingdir /bin $container
    buildah copy $container restest /bin/restest
    buildah copy $container /lib64/libpthread.so.0 /lib64
    buildah copy $container /lib64/libc.so.6 /lib64
    buildah copy $container /lib64/ld-linux-x86-64.so.2 /lib64
    buildah config --port 8000 $container
    #
    # This step is not working properly.
    # Need to run with podman -p 8000:8000 --entrypoint /bin/restest restest:latest
    buildah config --entrypoint /bin/restest $container
    buildah commit --format docker $container restest:latest
    

    This generates a 14MB container for a simple microservice! There are no additional files to be worrying about for vulnerabilities etc.

    I have a small defect I can't work out on entrypoints so I am overriding the entrypoint on start, but to test it run:

    podman -p8000:8000 --entrypoint /bin/restest restest:latest
    

    Then just type the following in a Terminal session:

    curl http://localhost:8000
    

    So thanks Dave C!