Docker as a platform provides the ability to package, ship, and run an application in an isolated environment called a container. This isolation allows running many containers simultaneously on a given host. Containers are lightweight and contain everything needed to run the application and no need to rely on what is currently installed on the host. It can also be easily shared while you work and be sure that everyone with whom we share gets the same container that works in the same way.
This article focuses on discussing how to use the predefined docker environment to run a sample C program step by step.
Step 1: Write a program
We will write a C program (dockerworld.c) which would be an application that can be run anywhere,
C
// C program to implement // the above approach #include <stdio.h> // Driver code int main() { printf ( "Welcome to Docker World!!!\n" ); return 0; } |
Step 2: Write a dockerfile
Here is the dockerfile to compile a C program.
FROM gcc:latest
COPY . /DockerWorld
WORKDIR /DockerWorld/
RUN gcc -o DockerWorld dockerworld.c
CMD [“./DockerWorld”]
Now let’s try to understand each line in the dockerfile before creating an image out of it,
1. FROM: We are using the default image developed by Docker Hub for GCC.
FROM gcc:latest
2. COPY all the local files directly into /DockerWorld inside the docker environment.
COPY . /DockerWorld
3. WORKDIR to set the current directory so that when the container runs, it knows the path from where to start the application.
WORKDIR /DockerWorld/
4. RUN to start the compilation of the C program dockerworld.c
RUN gcc -o DockerWorld dockerworld.c
5. CMD to instruct the docker to run the compiled version of C program once the container runs.
CMD [“./DockerWorld”]
The folder structure should be like the below,
DockerWorld/
-/ dockerfile
-/ dockerworld.c
Step 3: Create an image
The docker image needs to be built from the dockerfile.
docker image build -t docker-world-gcc /DockerWorld/
or
docker build -t docker-world-gcc /DockerWorld/
Once the image is built successfully, it can be checked in the docker image command,
Step 4: Run the container
Now run the container in interactive mode using the image built from GCC.
docker container run -it docker-world-gcc
or
docker run -it docker-world-gcc
The program now lives within an isolated layer on our local machine running docker inside an environment that compiles and runs GCC.
An image has been created in a host named node1, pushed to a docker hub, and ran the container in another host named node2. Please refer to docker push for steps to push an image to the docker hub.