Search code examples
cdockerdocker-composedockerfile

How to pack and ship a simple c application in docker without the gcc compiler?


I have a small c program application, I want to build a docker image for that and push it to docker hub and access on any platform. I want to achieve this within 50MB of image size. i.e. should be able to pack c application and run it without GCC compiler.

Please, it will be a great help if one can suggest a way to build an image within the size of 50MB. i.e without GCC compiler which is a dependency for c program to compile.

Also, suggest which is a best suitable base image for the c application.

NOTE: To build docker image i am using windows as host OS for docker. NOTE: it is a basic c program to add two number which i want to pack and ship.

I have already tried to create a docker image for c application which is of size 307MB. my goal is to build a docker image for c application in less than 50MB

MY dockerfile:

FROM busybox

COPY --from=rakeshchahar/rc-docker:my-image /usr/src/myapp usr/src/app/

WORKDIR /usr/src/app/

CMD ["./myapp"]  

I expect to build a image of size 50MB or less and want to access it on any platform.


Solution

  • You can use Alpine which is less then 5MB, In the case of multi-stage build, you can have the same bonus of 5MB

    Stage one: Compiling the source code to generate executable binary and

    Stage two: Running the result.

    # use alpine as base image
    FROM alpine as build-env
    # install build-base meta package inside build-env container
    RUN apk add --no-cache build-base
    # change directory to /app
    WORKDIR /app
    # copy all files from current directory inside the build-env container
    COPY . .
    # Compile the source code and generate hello binary executable file
    RUN gcc -o hello helloworld.c
    # use another container to run the program
    FROM alpine
    # copy binary executable to new container
    COPY --from=build-env /app/hello /app/hello
    WORKDIR /app
    # at last run the program
    CMD ["/app/hello"] 
    

    helloworld.c or replace with your own one

    #include <stdio.h>
    
    int main(){
       printf("Hello World!\n");
       return 0;
    }
    

    Another way to copy compiled code to your image which is also in just 5MB,

    FROM alpine:latest
    RUN mkdir -p /app
    COPY hello /app
    WORKDIR /app
    CMD ["/app/hello"]