docker 容器中不存在 postgres 数据库

postgres database doesn't exist in docker container

我的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

Docker文件是:

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;
    }
}

当我构建我的应用程序镜像时一切正常,然后我应该启动我的数据库镜像和应用程序镜像。我用 docker-compose up db 启动数据库,我得到:org.postgresql.util.PSQLException: FATAL: database "haircut_studio" does not exist。我的 DbConfig 有问题吗?如果我在本地启动我的应用程序,而不是在 Docker 容器中,我的应用程序会成功连接到数据库,我可以做任何我想做的事情。我该如何解决这个错误?

这是 GitLab 回购:https://gitlab.com/staaankey/java/-/tree/reservation-feature

默认数据目录是/var/lib/postgresql/data。 您需要调整音量:

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

您可以阅读更多相关信息