我正在做一个Java服务器作业,它有一个服务器和一个数据库。当我不使用 docker 时它们工作得很好。每次我尝试使用 docker-compose up 时,它都会告诉我服务器已退出,代码为 0。
这是我的 docker-compose.yaml:
version: '3.3'
services:
server:
build:
context: .
ports:
\- 8080:8080
depends_on:
\- db
environment:
\- POSTGRES_URL=jdbc:postgresql://db:5432/hw4
db:
image: postgres
restart: always
volumes:
\- db-data:/var/lib/postgresql/data
\- ./hw4.sql:/docker-entrypoint-initdb.d/hw4.sql
environment:
\- POSTGRES_DB=hw4
\- POSTGRES_USER=postgres
\- POSTGRES_PASSWORD=postgres
ports:
\- 5433:5432
healthcheck:
test: \[ "CMD", "pg_isready", "-U", "postgres" \]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
这是我的 Dockerfile:
# Use the official OpenJDK 17 image from Docker Hub
FROM openjdk:11-jdk AS build
# Set the working directory in the container
WORKDIR /app
# Copy the Gradle build files
COPY build.gradle settings.gradle gradlew /app/
COPY gradle /app/gradle
# Copy the source code
COPY src /app/src
# Copy the database dump file
COPY hw4.sql /docker-entrypoint-initdb.d/
# Build the application
RUN ./gradlew clean build
# Expose port 12345
EXPOSE 12345
# Define the command to run the application
CMD ["gradle", "run"]
每次运行 docker-compose up 时:
Starting erss-hwk3-db_1 ... done
Starting erss-hwk3-server_1 ... done
Attaching to erss-hwk3-db_1, erss-hwk3-server_1
db_1 |
db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization
db_1 |
db_1 | 2024-04-17 07:21:38.720 UTC [1] LOG: starting PostgreSQL 16.2 (Debian 16.2-1.pgdg120+2) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
db_1 | 2024-04-17 07:21:38.720 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
db_1 | 2024-04-17 07:21:38.720 UTC [1] LOG: listening on IPv6 address "::", port 5432
db_1 | 2024-04-17 07:21:38.725 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1 | 2024-04-17 07:21:38.742 UTC [29] LOG: database system was shut down at 2024-04-17 07:17:10 UTC
db_1 | 2024-04-17 07:21:38.750 UTC [1] LOG: database system is ready to accept connections
erss-hwk3-server_1 exited with code 0
也许这是因为 Dockerfile 中的
CMD
使用的是 gradle
,而不是 ./gradlew
。