Unofficial Content

Running a Java application using Docker Compose involves defining a Dockerfile for your Java application and creating a docker-compose.yml file to orchestrate the containers. Here's a basic guide on how to achieve this:

 
  1. Create a Dockerfile for your Java application:

Create a file named Dockerfile in the root directory of your Java application. This file will contain instructions for building your Docker image.

 

//dockerfile

# Use a base image with Java installed

FROM openjdk:11

 

# Set the working directory inside the container

WORKDIR /app

 

# Copy the compiled Java application JAR file into the container

COPY target/your-application.jar /app/your-application.jar

 

# Command to run the Java application

CMD "java", "-jar", "your-application.jar"
 

Replace your-application.jar with the actual name of your compiled Java application JAR file.

 
  1. Create a docker-compose.yml file:

Create a file named docker-compose.yml in the root directory of your project. This file will define the services required to run your Java application.

 

//yaml

version: '3'

services:

  app:

    build: .

    ports:

      - "8080:8080"
 

This docker-compose.yml file defines a single service named app. It builds the Docker image using the Dockerfile in the current directory (.) and maps port 8080 on the host to port 8080 in the container.

 
  1. Build and run the Docker containers using Docker Compose:

Open a terminal in the directory containing your Dockerfile and docker-compose.yml file.

Run the following command to build the Docker image and start the containers:

 

//css

docker-compose up --build
 

Docker Compose will build the Docker image based on the Dockerfile and start the container for your Java application. You should see the output of your Java application in the terminal.

 
  1. Access your Java application:

Once the container is up and running, you can access your Java application by navigating to http://localhost:8080 in your web browser.

Below you can find an example of a dockerfile:

version: '3.8'
services:
  db:
    image: mysql:8.0
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_DATABASE: 'mybdname'
      MYSQL_USER: 'user'
      MYSQL_PASSWORD: 'password'
      MYSQL_ROOT_PASSWORD: 'rootpassword'
    ports:
      - "3306:3306"
    volumes:
      - db_data:/var/lib/mysql

  app:
    image: mygxapp-javaapp
    depends_on:
      - db
    ports:
      - "1010:8080"
    environment:
      GX_DEFAULT_DB_USER_ID=user
      GX_DEFAULT_DB_PASSWORD=password
      GX_DEFAULT_DB_URL=jdbc:mysql://db:3306/mybdname?useSSL=false

  volumes: db_data:

 

Last update: February 2024 | © GeneXus. All rights reserved. GeneXus Powered by Globant