Postgres 数据库在 docker 容器中不存在



我的docker-compose。yml:

version: "3.9"
services:
db:
image: postgres
restart: always
ports:
- "5432:5432"
environment:
POSTGRES_PASSWORD: 123
POSTGRES_DB: "haircut_studio"
POSTGRES_USER: "postgres"
volumes:
- ./log-directory:/var/lib/postgresql
app:
build: ../
restart: always
ports:
- "8080:8080"
environment:
- DATASOURCE_HOST=db
- DATASOURCE_PORT=5432
depends_on:
- db

Dockerfile是:

FROM openjdk:17-alpine
COPY / /spd
WORKDIR /spd
RUN chmod +x gradlew
RUN ./gradlew :bootJar
WORKDIR /spd/build/libs
EXPOSE 8080
CMD ["java","-jar", "haircutStudio-0.0.1-SNAPSHOT.jar"]

application.properties

spring.jpa.show-sql=true
#logging.level.root=debug
server.port=8080
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
datasource.username=postgres
datasource.password=123
datasource.host=localhost
datasource.port=5432
datasource.url=jdbc:postgresql://${datasource.host}:${datasource.port}/haircut_studio
spring.datasource.driver-class-name=org.postgresql.Driver
spring.flyway.baselineOnMigrate = true
logging.level.org.springframework.boot.autoconfigure=ERROR

TestDbConfig.java

package com.spdu.haircutstudio.configuration;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DbConfig {
@Bean(destroyMethod = "close")
public DataSource getDataSource(
@Value("${datasource.password}") String password,
@Value("${datasource.username}") String username,
@Value("${datasource.url}") String jdbcUrl
) {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(jdbcUrl);
config.setUsername(username);
config.setPassword(password);
return new HikariDataSource(config);
}
@Bean
public Flyway flyway(DataSource dataSource) {
final Flyway flyway = Flyway.configure()
.dataSource(dataSource)
.locations("classpath:db")
.outOfOrder(true)
.load();
flyway.migrate();
return null;
}
}

当我建立我的应用程序的图像一切都是好的,然后我应该启动我的db图像和应用程序的图像。我从docker-compose up db开始,得到:org.postgresql.util.PSQLException: FATAL: database "haircut_studio" does not exist。我的DbConfig有问题吗?如果我在本地启动我的应用程序,而不是在Docker容器中,我的应用程序成功连接到DB,我可以做我想做的一切。我如何修复这个错误?

这里是GitLab的repo: https://gitlab.com/staaankey/java/-/tree/reservation-feature

默认数据目录为"/var/lib/postgresql/data"你需要调整音量:

volumes:
- ./log-directory:/var/lib/postgresql/data

你可以在这里阅读更多信息

最新更新