Search code examples
cdockerdocker-composedockerfile

How to use Docker compose in c program?


I want to isolate my development environment to create a project in C. But I don't know how to use Docker with C. I'm getting confused about running the program and I would like someone to help me. Take for example a "hello world" with an input. basic as a program. How can I make a docker compose and how to run it. And still with live-reload?

hello.c:

#include <stdio.h>
int main() {
  int numero;

  // Pede um número ao usuário
  printf("Digite um número: ");
  scanf("%d", &numero);

  // Exibe o número digitado na tela
  printf("O número digitado foi: %d\n", numero);

  return 0;
}

Dockerfile:

FROM gcc:latest

COPY . /app

WORKDIR /app/

RUN gcc -o app hello.c

CMD [“./app"]


Solution

  • It's good practice (although not required) to treat containers as immutable.

    In this scenario, whenever your code changes, you rebuild and create a uniquely new image.

    There are various ways to work with mutable containers:

    1. Use a container interactively e.g. Bash to edit the code, compile it etc.
    2. Mount host files into a container (possibly in combination with #1)
    3. Copy files in|out of a running container

    Some combination of these approaches may serve your needs but be careful to ensure you do so correctly so that you persist changes to files in the container:

    You can create an interactive shell on a container from the gcc:latest image and mount files e.g. your source code into a folder on it:

    WORK="/app"
    
    docker run \
    --interactive --tty --rm \
    --volume=${PWD}/hello.c:${WORK}/hello.c \
    --workdir=${WORK} \
    gcc:latest
    

    This will mount ${PWD}/hello.c into the container's /app folder and make this the working directory.

    When you run the docker command, you should see:

    # ls
    hello.c
    

    You can then:

    # gcc -o hello hello.c
    # ls 
    hello hello.c
    # ./hello
    Digite um número: 55
    O número digitado foi: 55
    

    Any changes you make to hello.c (only) will be reflected in the copy on your host.