Skip to content

Instantly share code, notes, and snippets.

@chongshenng
Last active March 23, 2023 14:39
Show Gist options
  • Select an option

  • Save chongshenng/0a99f8d46b39bb045aeb5f19604c170d to your computer and use it in GitHub Desktop.

Select an option

Save chongshenng/0a99f8d46b39bb045aeb5f19604c170d to your computer and use it in GitHub Desktop.
Build Docker container with secrets

Sometimes you want to build a Docker image with secrets. To do so, you should use BuildKit and add this line to the start of your Dockerfile:

syntax=docker/dockerfile:1.4

Then, if you have the secrets as an environment variable in your local machine, do:

$ export MYSECRET=theverysecretpassword
$ export DOCKER_BUILDKIT=1
$ docker build --secret id=mysecret,env=MYSECRET .

If the ID and environment variable has the same name, do:

$ docker build --secret id=MYSECRET .

Ref:

Example tying GitHub workflow, secrets, and Dockerfile

    - name: Build the Docker image
      uses: docker/build-push-action@v4
      with:
          context: .
          file: Dockerfile
          tags: |
            ${{ first_tag }}
            ${{ second_tag }}
          push: false
          secrets: |
            "GH_TOKEN=${{ secrets.GH_TOKEN }}"

And in the Dockerfile

# syntax = docker/dockerfile:1.4

...

RUN --mount=type=secret,id=GH_TOKEN \
    /code/.venv/bin/pip install git+https://$(cat /run/secrets/GH_TOKEN)@github.com//username/private-repository.git
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment