Search notes:

Create a Docker image FROM SCRATCH

The C Program

This is the source of the C program whose compiled executable we want to run in a docker container:
#include <stdio.h>
#include <unistd.h>
#include <sys/utsname.h>

int main() {
   printf("This program runs in (or as?) a container\n");
   printf("The processid (PID) is %d\n", getpid());

   struct utsname unam;
   if (uname(&unam) != -1) {
       printf("Kernel version and release:\n  %s\n  %s\n", unam.version, unam.release);
   } else {
       printf("Failed to retrieve kernel information.\n");
   }
}
Github repository about-Docker, path: /image/create/from-scratch/prog.c

Compiling the program

We need to compile the program. I believe the -static flag is rather important because SCRATCH comes empty, i. e. without any C standard libraries. (But I should verify this assumption of mine):
gcc -static prog.c -o prog
Github repository about-Docker, path: /image/create/from-scratch/1-compile-prog

Building the image from the executable and a dockerfile

This is the Dockerfile we use to create the image …
FROM      scratch
ADD       prog     /
CMD   [ "/prog"    ]
Github repository about-Docker, path: /image/create/from-scratch/Dockerfile
… and the image is built with the following comand:
docker build -t prog-img .
Github repository about-Docker, path: /image/create/from-scratch/2-build-image

Run the image

Now, we can run the image:
docker run prog-img
Github repository about-Docker, path: /image/create/from-scratch/3-run-image

See also

image

Index