An example of creating a Docker image using Pipelines and pushing the newly created Docker image to AWS ECR.
Scenario: You are using an AWS container service and need to build a Docker image to deploy it to.
Starting off, we’ll create a blank file bitbucket-pipelines.yml in the root of our project and copy in the below template.
- Line 1 under image, we define the default image each build step will use.
- Line 4 under definitions, we define our build steps and their logic.
- Line 6 under pipelines, we define when our build steps will be triggered.
From here we can add our first build step and trigger. Our first build step will handle the building of the image and pushing it to AWS ECR. Next, we will set up our trigger, so when changes are pushed/merged into the master branch it will run the build image step.
Build step breakdown (lines 6 to 18):
- Line 6 is the user-friendly name that is shown in Bitbucket.
- Line 7 defines dependencies to cache on the Bitbucket servers to reduce build time.
- Line 9 defines services to use with the build step, those are run in separate but linked containers.
- Line 11 defines the commands to run for this build step.
Build step script breakdown (from line 12):
- Line 12 is where we make the image URI, including both the path to where its located and the tag.
- Line 14 we are running “aws ecr get-login” to retrieve the docker login command with the correct credentials, then using eval to run the returned command.
- Line 16 builds the Docker image while at the same time tags it.
- Lastly, line 18 pushes the newly created image to AWS ECR.
At this point, you may be thinking wait where are the variables DOCKER_IMAGE_URL and BITBUCKET_BUILD_NUMBER defined?
Bitbucket pipelines provides a set of default variables, those variables start with BITBUCKET, which makes it easy to differentiate them for user-defined variables. DOCKER_IMAGE_URL, on the other hand, needs to be defined within Bitbucket along with 3 other variables, this can be done by:
- Going to your repository in Bitbucket
- Clicking on Settings in the second left menu bar
- And clicking on Repository variables under the Pipelines heading
The 4 user-defined variables:
Now that you have completed all that, you are ready to go on and add additional build steps to have a streamline build and deploy workflow.
As a bonus, I’ve included an example pipelines file that will:
- Run composer install (for PHP).
- Build a Docker image.
- Upload a beanstalk artifact.
- Deploy to Staging and Production.
Below that is a link to my example repository.