Pages

Wednesday, March 13, 2019

Docker - Get Code inside a Container


One common situation that i run into on different projects is how to tell my docker container to clone or pull code automatically. In this article we will see the various ways of getting the code to the Docker container.

There are 3 ways of getting code into the docker container.

1. Using COPY or ADD command - Docker provides both COPY and ADD instructions for adding files/code to the docker image. A simple Dockerfile will look something like this,

FROM ubuntu
MAINTAINER "jagadish Manchala"

#Add all files available at current location
COPY . /home/sampleTest

#Set working directory
WORKDIR /home/sampleTest

The source code needs to be cloned to the current directory where the Dockerfile exists. Once we build the docker image, the code is copied to the /home/sampleTest directory and will be available once we run the container. ADD and COPY both works similarly. ADD command has the extra capability of fetching remote urls and extracting tarballs. COPY and ADD techniques are most commonly used in production to build production ready docker images

2. Using the Volume Feature - The second method is the most commonly used way of sharing local content with the container. Using volumes we can mount a local directory to the container at runtime. The running container can share the files with the host machine.

We need to checkout the latest source code to a directory and mount the directory as a volume to the running container. This can be done as,
docker run -d --name my-source-project -v "$PWD":/tmp gitdocker

This command start a container attaching the current working directory mounted as a volume to the container on /tmp. 

This is commonly used feature when developing code. We can use a favourite editor to edit the code locally and then attach the directory as a volume to the running container and check the changes

3. Using the GIT clone directly - The last method is to run the git clone command directly. Docker provides the RUN instruction to execute the commands directly inside the container while building the image. We can use the RUN instruction with the “git clone” command in the Dockerfile as below,

FROM ubuntu
MAINTAINER "jagadish Manchala"

#Install git
RUN apt-get update \
       apt-get install -y git

RUN mkdir /home/sampleTest \
       cd /home/sampleTest \
       git clone https://github.com/jagadish12/SampleTest.git

#Set working directory
WORKDIR /home/sampleTest

Though this gives a security risk we can pull the public github repo directly into the docker image while building. The code will be available when we start the container.

More to Come, Happy Learning :-)

No comments :

Post a Comment