22

Part of our CI/CD workflow tags Docker images with the git branch's name. However, the set of valid characters for docker tags is smaller than the set of valid characters for a git branch name.

As a very simple example, the branch name bugfix/my_awesome_feature is not a valid tag:

docker build . -t image_name:$(git rev-parse --abbrev-ref HEAD)

Fails with the error that it is "not a valid repository/tag: invalid reference format".

Same with more complicated branch names: fix/bug#123, pr@123, etc....

What's the best way to turn a git branch name into a valid docker tag? Ignoring or replacing all invalid characters is fine.

2 Answers 2

22

Docker tag does not allow most of the special character except -,_,..

A tag name must be valid ASCII and may contain lowercase and uppercase letters, digits, underscores, periods and dashes. A tag name may not start with a period or a dash and may contain a maximum of 128 characters.

docker valid image tags

So you can replace all special character with -. in your Branch name.

docker build . -t image_name:$(git rev-parse --abbrev-ref HEAD | sed 's/[^a-zA-Z0-9]/-/g') 

So the following branch will become

fix/bug#123 -> fix-bug-123  
pr@123 -> pr-123

You can replace - with underscores, periods and dashes

#to use `_`
sed 's/[^a-zA-Z0-9]/_/g'
3
  • 1
    I ended up keeping only the allowed characters (alphanumeric, dots, dashes, and underscores) with: sed 's/[^[:alnum:]\.\_\-]/-/g'. Everything else gets converted to a dash here.
    – Felix
    Commented Sep 25, 2020 at 20:55
  • how to make it in GitLab ci/cd? Commented Nov 12, 2020 at 14:47
  • 1
    @catscoolzhyk in Gitlib you can use CI_COMMIT_REF_SLUG instead of branch name to avoid workaround. "$CI_COMMIT_REF_NAME lowercased, shortened to 63 bytes, and with everything except 0-9 and a-z replaced with -. No leading / trailing -. Use in URLs, host names and domain names" docs.gitlab.com/ee/ci/variables/predefined_variables.html
    – Adiii
    Commented Nov 13, 2020 at 2:21
17

When using GitLab CI, you can use a predefined variable CI_COMMIT_REF_SLUG, description:

$CI_COMMIT_REF_NAME lowercased, shortened to 63 bytes, and with everything except 0-9 and a-z replaced with -. No leading / trailing -. Use in URLs, host names and domain names.

Source

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.