Q:

Get branch name in Dockerfile

In my Dockerfile I copy and build my frontend:
FROM node:8.11 as frontend
COPY frontend/package.json /frontend/package.json
COPY ./VERSION /frontend/VERSION
WORKDIR /frontend
RUN npm install
COPY frontend/ /frontend
RUN sed -i "s|VERSION|frontend@$(cat "VERSION")|g" src/environments/environment.prod.ts
RUN npm run build-prod

I want to change the following line:
RUN sed -i "s|VERSION|frontend@$(cat "VERSION")|g" src/environments/environment.prod.ts

to have a branch name at the beginning so it would look like:
RUN sed -i "s|VERSION|`**BRANCH_NAME**`-frontend@$(cat "VERSION")|g" src/environments/environment.prod.ts

so I want to get Branch name in my dockerfile somehow. 
but I'm not sure is it possible to use branch/commit names in dockerfile?
this is my gitlab-ci.yaml file: 
build:
  stage: build
  before_script:
    - docker login -u gitlab-ci-token -p "$CI_JOB_TOKEN" registry.xx.xx
  script:
    - export TARGET=frontend
    - export IMAGE=$CI_REGISTRY_IMAGE/$TARGET
    - docker pull $IMAGE:$CI_COMMIT_REF_NAME || echo "no branch image"
    - docker pull $IMAGE:latest || echo "no latest image"
    - docker build --target $TARGET -t $IMAGE:$CI_COMMIT_REF_NAME .
    - docker push $IMAGE:$CI_COMMIT_REF_NAME

    - export IMAGE=$CI_REGISTRY_IMAGE
    - docker pull $IMAGE:$CI_COMMIT_REF_NAME || echo "no branch image"
    - docker pull $IMAGE:latest || echo "no latest image"
    - docker build -t $IMAGE:$CI_COMMIT_REF_NAME .
    - docker push $IMAGE:$CI_COMMIT_REF_NAME
  tags:
    - local-docker

A:

What you can do is add an ARG in your Dockerfile called BRANCH_NAME and pass it in with --build-arg.
Below will create a build arg that defaults to master if no build arg is passed to the docker build:
FROM node:8.11 as frontend

ARG BRANCH_NAME=master
...
...

Your pipeline will include a docker build step like the following:
docker build -t $IMAGE:$CI_COMMIT_REF_NAME --build=arg BRANCH_NAME=$CI_COMMIT_REF_NAME .

From there, you can use the argument as a variable in your Dockerfile.

