Home > Software design >  How to checkout at particular commit in Dockerfile?
How to checkout at particular commit in Dockerfile?

Time:12-20

I am writing a Dockerfile for my project like

RUN git clone https://github.com/CNA/contract.git --depth 1 --branch 20.0 /opt/CNA-contract

I would like to freeze the code at a particular commit. What is the best practice to do something like this in Docker? I see it fairly easy in buildouts something like

git clone https://github.com/CNA/contract.git --depth 1 --branch 20.0 /opt/CNA-contract commit-SHA

CodePudding user response:

It would better to add a few steps in your RUN, as described in "How to shallow clone a specific commit with depth 1?", assuming a recent version of Git 2.24 or mroe:

RUN \
mkdir repo && \
cd repo && \
git init . && \
git remote add origin <url> && \\
git fetch --depth 1 origin <sha1> && \\ 
git checkout FETCH_HEAD

That way, you only fetch the commit you need.

CodePudding user response:

If you don't run git clone in your Dockerfile but rather on the host, then you can check out and build whatever commit you want.

# on the host, not in a Dockerfile
git clone https://github.com/CNA/contract.git
cd contract
git checkout 20.0
docker build -t cna/contract:20.0 .
git checkout main
docker build -t cna/contract:$(git rev-parse --short HEAD)

This approach also avoids some dangerous problems around getting appropriate credentials to run the git clone command (that repository isn't public; can you use docker run to get a private key back out of the image?), it supports building things that aren't actually committed to source control, and it avoids some problems with Docker layer caching where Docker won't repeat a git clone command even if the repository has changed.

  • Related