Build an Image with Build Arguments
Use docker argument in Codefresh pipelines
Building a Docker image that requires build arguments is very easy with Codefresh pipelines.
The source code of the repository is located at https://github.com/codefreshdemo/cf-example-build-arguments. Feel free to fork it if you want to follow along.
If you don’t already have a Codefresh account, you can easily create a free one from the sign-up page.
Using Docker build arguments
The example application is a very simple NodeJS application with the following dockerfile:
Dockerfile
ARG NODE_VERSION
FROM node:$NODE_VERSION
ARG APP_DIR
RUN mkdir -p $APP_DIR
WORKDIR $APP_DIR
COPY package.json .
RUN npm install --silent
COPY . .
EXPOSE 3000
ENV PORT 3000
CMD [ "npm", "start" ]
This Dockerfile expects two build arguments:
NODE_VERSION
is the version of Node image to use as baseAPP_DIR
is the source directory to be used inside the container
Building a Dockerfile passing values for build arguments
When you build an image locally on your workstation you can define build arguments with the --build-arg
syntax:
docker build . -t my-node-app --build-arg NODE_VERSION=8 --build-arg APP_DIR=/usr/src/app
The same thing can also be achieved within a Codefresh pipeline:
codefresh.yml
version: '1.0'
steps:
main_clone:
title: Cloning main repository...
type: git-clone
repo: 'codefreshdemo/cf-example-build-arguments'
revision: 'master'
git: github
build_my_app:
title: Building Node.Js Docker Image
type: build
image_name: my-app
working_directory: '.'
tag: 'master'
dockerfile: Dockerfile
build_arguments:
- NODE_VERSION=8
- APP_DIR=/usr/src/app
This pipeline checks out the source code of the repository and then builds the Dockerfile by passing the values 8
and /usr/src/app
to the two arguments.
Using Codefresh variables as build arguments
In the previous pipeline the docker build arguments are defined in the pipeline itself, but you could also use pipeline variables, shared configuration or any other standard mechanism you already have in place.
codefresh.yml
version: '1.0'
steps:
main_clone:
title: Cloning main repository...
type: git-clone
repo: 'codefreshdemo/cf-example-build-arguments'
revision: 'master'
git: github
build_my_app:
title: Building Node.Js Docker Image
type: build
image_name: my-app
working_directory: '.'
tag: 'master'
dockerfile: Dockerfile
build_arguments:
- NODE_VERSION=${{NODE_VERSION_FROM_SHARED_CONFIG}}
- APP_DIR=${{APP_DIR_PIPELINE_VARIABLE}}
In this case you can also use any of the built-in Codefresh variables.