GitLab CI: Using a private project's container in a Dockerfile
In GitLab, if you have a Container Registry set up for a private project (“Project A”), and you wish to use one of those containers in the FROM <image>
field of a Dockerfile
in another project (“Project B”) to create a new container, which you will then push to Project B’s Container Registry, e.g.:
Then you might get a 403 Forbidden
error as follows:
The problem is that the instance of Docker running in Project B’s container does not have permission to access Project A’s Container Registry, even if both projects are part of the same group.
This is subtly different from the previous note about using the container as an image:
within GitLab CI, because this time it is not the GitLab Runner trying to pull the images, but the Docker process running within the container launched by the GitLab Runner.
You can fix this by using docker login
to authenticate with Project A’s Container Registry before doing docker build
. Then you have to do docker logout
and docker login
to Projet B’s Container Registry before being able to docker push
the new container to Project B’s Container Registry.
The steps are as follows:
- On Project A (the one with the Container Registry), go to Settings > Access Tokens.
- Choose a token name, e.g.
ci_pull_containers
. - Set role to “Developer”.
- Check the box for
read_registry
. - Click “Create project access token”:
- On Project B (the one wanting to access Projet A’s Container Registry), go to Settings > CI/CD > Variables.
- Click Add variable to open up a modal.
- Set the key as
PROJECT_A_REGISTRY_USER
and paste the token name, e.g.ci_pull_containers
. - Click Add variable to save the new variable.
- Click Add variable to open up a modal.
- Set the key as
PROJECT_A_REGISTRY_PASSWORD
and paste the access token. - Click Add variable to save the new variable.
- Modify your
.gitlab-ci.yml
todocker login
toyour.gitlab.address.com:5000
usingPROJECT_A_REGISTRY_USER
andPROJECT_A_REGISTRY_PASSWORD
, and thendocker logout
anddocker login
asCI_REGISTRY_USER
(which is automatically created by GitLab CI for read-write access to the project’s own Container Registry):
- That’s it! CI jobs run on Project B will now be able to access images from Project A in the
Dockerfile
, and then push them to their own (Project B’s) Container Registry. - Note that when the token expires you will need to create a new one and update
PROJECT_A_REGISTRY_PASSWORD
.