Sunday, 7 May 2023

Running Spring boot app with MySQL in docker container

Create a Dockerfile and add the following contents.


 FROM openjdk:11
 LABEL AUTHOR="shahzeb"
 ARG BUILD_FILE=target/pos-1.0.jar
 COPY ${BUILD_FILE} pos.jar     
 ENTRYPOINT [ "java", "-jar", "/pos.jar" ]
 EXPOSE 8080
 

To build the docker image, run the following command.

        
            docker build -t [docker image name] .
            docker build -t shahzeb/pos .
        
    

To run the container from the image created from above command, run the following command

                
            

docker run -p 8080:8080 shahzeb/pos --network=host

        
            

docker container run --network pos-app-env --name pos-app -p 8080:8080 -d shahzeb/pos

The --network parameter is use to connect the spring boot application to the mysql database on the host machine. Since we are already using the EXPORT 8080 for exposing the port. we can skip passing -p 8080:8080 to the docker run command.

docker network create [network name.] #Create a network on which the app will run

        
            

docker network create pos-app-env

        
            

docker container run --network [netowrk name] --name [container name] -p 8080:8080 -d [docker image name]

        
            

docker container run --network pos-app-env --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=str0ng -d mysql:8.0

        
            

# Running pos in docker environment

To run the application in docker env, run the following 4 commands.

Create a network in docker

        
            

docker network create pos-app-env

Start MySQL in same network

        
            

docker container run --network pos-app-env --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=str0ng -d mysql:8.0

Build Docker Image container POS app

        
            

docker build -t shahzeb/pos .

Run Container for the app

        
            

docker container run --network pos-app-env --name pos-app -p 8080:8080 -d shahzeb/pos

Using docker-compose file.


version: '3.9'
services:
  mysqldb:
    image: mysql:8.0
    ports:
      - "3306:3306"
    networks:
      - pos-app-env
    environment:
      - MYSQL_ROOT_PASSWORD=str0ng
      - MYSQL_DATABASE=pos
    restart: always
    healthcheck:
      test: [ "CMD", "mysqladmin", "ping", "-h", "localhost" ]
      timeout: 20s
      retries: 10

  pos-app:
    image: shahzeb/pos
    ports:
      - "8080:8080"
    networks:
      - pos-app-env
    depends_on:
      - mysqldb

networks:
  pos-app-env:


No comments:

Post a Comment