Creating a Docker image

Creating a Docker image

Create a new Dockerfile for your project. We will place this in docker/Dockerfile to avoid clashes with Elastic Beanstalk later on.

Use the following content for this:

FROM tomcat:9.0

ARG VERSION
ENV PROJECT_VERSION=$VERSION

COPY build/libs/workshop-java-docker-aws.war /usr/local/tomcat/webapps/counter.war

COPY docker/docker-run.sh /docker-run.sh
CMD ["/docker-run.sh"]

Please also make sure to have a file docker/docker-run.sh. It should have a content as follows:

#!/usr/bin/env bash

echo "Starting docker container"

export EC2_INSTANCE_ID="$(curl http://169.254.169.254/latest/meta-data/instance-id)"

exec catalina.sh run

Set the executable bit on the file:

chmod +x docker/docker-run.sh

Enhance the Makefile of the project as follows:

AWS_REGION          := eu-central-1
SERVICE             := java-docker-aws-example
CI_AWS_ACCOUNT_ID   := 1234

GIT_SHA             ?= $(shell git rev-parse --short HEAD)
VERSION             := $(GIT_SHA)
DOCKER_REGISTRY     := $(CI_AWS_ACCOUNT_ID).dkr.ecr.$(AWS_REGION).amazonaws.com
DOCKER_IMAGE        := $(DOCKER_REGISTRY)/$(SERVICE):$(VERSION)

###############################################################################################

.PHONY: docker-build
docker-build: build
	docker build -t $(DOCKER_IMAGE) --build-arg VERSION=$(VERSION) -f docker/Dockerfile .

This should allow you to build a Docker image with the following command:

make docker-build

Running the project locally

In order to run the project locally we will use Docker Compose.

Create a file docker-compose.yml in the project. It should have the following content:

version: '3'

services:
  webapp:
    build:
      context: .
      dockerfile: docker/Dockerfile
      args:
        VERSION: "${VERSION}"
    restart: always
    ports:
      - "8080:8080"
    environment:
      MYSQL_HOST: db
      MYSQL_DATABASE: counter
      MYSQL_USER: counter
      MYSQL_PASSWORD: counter
  db:
    image: mysql:5.7
    restart: always
    ports:
      - "3306:3306"
    environment:
      MYSQL_DATABASE: counter
      MYSQL_USER: counter
      MYSQL_PASSWORD: counter
      MYSQL_ROOT_PASSWORD: example

Enhance the Makefile of the project as follows:

.PHONY: docker-run
docker-run: build
	VERSION=$(VERSION) docker-compose build
	VERSION=$(VERSION) docker-compose up

Now you could run the application with local Docker containers by using the following command:

make docker-run

Check out http://localhost:8080/counter/ in your Browser to see if everything works as expected.
You could also use curl for this:

curl -i http://localhost:8080/counter/