CI/CD using Docker, Travis CI, ECS, and Python

CI/CD using Docker, Travis CI, ECS, and Python

I am going to take you through the steps setting up an environment for automated building, testing, and deployment, using containers and services hosted in the cloud.

What we need:

When a commit or a merge is done to a branch, this will trigger Travis and run a list of instructions to build and run our tests. If the build is done successfully and every test passes, Travis will push our Docker image to Docker Hub and trigger an update event on ECS telling to our cluster that it has a new image version to be downloaded.

Our Python application consists of two files. main.py contains our Flask code and then requirements.txt which will layout dependencies etc.

Now let’s build a Dockerfile and a docker-compose for our Python code and upload it to Docker Hub.

Now it’s time to create the image and push it to Docker Hub.

$ docker-compose build --pull
$ docker-compose push

You should see something similar to this when complete:

a successful build

and it’s now been pushed to Docker Hub….

Let’s check

There it is!

Now it’s time to log in to Travis-CI with your GitHub account.This will sync your repositories.

We will need to create .travis.yml and travis-deploy.sh scripts:

Now we approach the ECS portion…

Choose a name for the container. for image, use the following format:

Docker Hub username/Repository name:latest

Also, under port mappings make sure you specify 8000.

Then under Load Balancer type, choose Application Load Balancer.

Choose a cluster name.

Review and create.

Now on to Travis CI…

You will see your GitHub repo you have your travis file uploaded to. it will detect it and run the file.

We have to set up our environment variables in Travis. Under your project, go to settings.

this is what they should look like

Now, on AWS go to EC2>load balancer>Basic Configuration, copy your DNS. Copy the DNS name and paste in your browser with the port 8000.

You will see the text we set up earlier

text we entered into main.py

Let’s go ahead and put everything to the the test! Make a change to the text and commit. You can see events put in motion on Travis.

Refresh and see the update — It worked!

After building and testing Travis will deploy our image to Docker Hub and notify ECS that there’s a new version. You have now created your own CI/CD environment! Thanks for reading and following along. Share what you’re working on in the comments.

I have uploaded all my files to GitHub so you can follow along.