Efficient Docker Builds: Pulling Git Repositories Directly in Dockerfiles
docker node.js

Efficient Docker Builds: Pulling Git Repositories Directly in Dockerfiles

Marcell Simon
Marcell Simon

When building Docker images, it's common to pull code directly from a Git repository. This guide will walk you through setting up your Dockerfile to pull from private repositories in GitLab and GitHub, using SSH keys for secure access.

A sample node.js application for the demo:

Setting Up for GitLab

  1. Generate SSH Keys: Use ssh-keygen to generate a new SSH key pair if you don't already have one.
  2. Add SSH Key to GitLab: In your GitLab account, add the public key to your user settings under "SSH Keys."
  3. Prepare the SSH Folder: Ensure you have an SSH folder with your keys ready to be copied into your Docker image.

Setting Up for GitHub

  1. Generate SSH Keys: As with GitLab, generate your SSH keys if you haven't already.
  2. Add SSH Key to GitHub: In your GitHub account, add the public key to your settings under "SSH and GPG keys."
  3. Prepare Your SSH Folder: Similar to GitLab, prepare an SSH folder for your Docker image.

Creating the Dockerfile

Your Dockerfile will look similar for both GitLab and GitHub, with slight modifications for the repository URL. Here's a generalized version:

FROM ubuntu:latest
WORKDIR /app

# Install git and other dependencies
RUN apt-get update && \
    apt-get install -y git

# Authorize SSH Host
RUN mkdir -p /root/.ssh && \
    chmod 0700 /root/.ssh && \
    ssh-keyscan [gitlab.com|github.com] > /root/.ssh/known_hosts

# Add the keys and set permissions
COPY ./ssh/id_rsa /root/.ssh/id_rsa
RUN chmod 600 /root/.ssh/id_rsa

# Clone your project
RUN git clone git@[gitlab.com|github.com]:username/repository.git

WORKDIR /app/repository

# Install project dependencies
RUN npm install

# Any additional setup here

Note: Replace [gitlab.com|github.com] with gitlab.com or github.com and username/repository.git with your specific repository details.

GitLab and GitHub Specifics

  • For GitLab: Make sure you've added the SSH key to your GitLab account and authorized gitlab.com as a known host in your Dockerfile.
  • For GitHub: Ensure the SSH key is added to your GitHub account, and github.com is recognized as a known host.

Conclusion

By setting up your Dockerfile to pull from private Git repositories, you streamline your build process and ensure your Docker images are always up to date with the latest code. Remember to secure your SSH keys and verify the repository URLs for GitLab or GitHub accordingly.


Photo by Anete Lusina