2

Мое приложение построено на Spring Boot и у меня есть некоторая проблема с запуском его в Docker Compose. Я использую Luquibase для построения таблиц и он не хочет их создавать, причем эта проблема есть только при запуске docker-compose up — то есть если я просто запущу свой проект без Docker, то все таблицы успешно создаются.

Если вдруг нужны ещё какие то подробности — спрашивайте. Оперативно отвечу.

Dockerfile

FROM openjdk:11
ADD target/dexterity.jar dexterity.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "dexterity.jar"]

Stacktrace

postgres | 2021-05-10 07:24:46.833 UTC [33] ERROR:  relation "credential" already exists
postgres | 2021-05-10 07:24:46.833 UTC [33] STATEMENT:  CREATE TABLE public.credential (id BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, login VARCHAR(32) NOT NULL, experience BIGINT NOT NULL, email VARCHAR(128) NOT NULL, passwo
rd VARCHAR(255) NOT NULL, role VARCHAR(32) NOT NULL, file_name VARCHAR(1024), CONSTRAINT CREDENTIAL_PKEY PRIMARY KEY (id), UNIQUE (login))
dexterity | 2021-05-10 07:24:46.839 ERROR 1 --- [           main] liquibase.changelog.ChangeSet            : Change Set classpath:db/changelog/db.changelog-master.yaml::1::ulxanxv failed.  Error: ERROR: relation "credential" already
 exists [Failed SQL: (0) CREATE TABLE public.credential (id BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, login VARCHAR(32) NOT NULL, experience BIGINT NOT NULL, email VARCHAR(128) NOT NULL, password VARCHAR(255) NOT NULL, role
VARCHAR(32) NOT NULL, file_name VARCHAR(1024), CONSTRAINT CREDENTIAL_PKEY PRIMARY KEY (id), UNIQUE (login))]
dexterity | 2021-05-10 07:24:46.844  INFO 1 --- [           main] l.lockservice.StandardLockService        : Successfully released change log lock
dexterity | 2021-05-10 07:24:46.846  WARN 1 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCre
ationException: Error creating bean with name 'liquibase' defined in class path resource [org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration$LiquibaseConfiguration.class]: Invocation of init method failed; n
ested exception is liquibase.exception.MigrationFailedException: Migration failed for change set classpath:db/changelog/db.changelog-master.yaml::1::ulxanxv:
dexterity |      Reason: liquibase.exception.DatabaseException: ERROR: relation "credential" already exists [Failed SQL: (0) CREATE TABLE public.credential (id BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, login VARCHAR(32) NOT
NULL, experience BIGINT NOT NULL, email VARCHAR(128) NOT NULL, password VARCHAR(255) NOT NULL, role VARCHAR(32) NOT NULL, file_name VARCHAR(1024), CONSTRAINT CREDENTIAL_PKEY PRIMARY KEY (id), UNIQUE (login))]
dexterity | 2021-05-10 07:24:46.847  INFO 1 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
dexterity | 2021-05-10 07:24:46.867  INFO 1 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
dexterity | 2021-05-10 07:24:46.872  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
dexterity | 2021-05-10 07:24:46.888  INFO 1 --- [           main] ConditionEvaluationReportLoggingListener :
dexterity |
dexterity | Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
dexterity | 2021-05-10 07:24:46.910 ERROR 1 --- [           main] o.s.boot.SpringApplication               : Application run failed
dexterity |
dexterity | org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration$LiquibaseConf
iguration.class]: Invocation of init method failed; nested exception is liquibase.exception.MigrationFailedException: Migration failed for change set classpath:db/changelog/db.changelog-master.yaml::1::ulxanxv:
dexterity |      Reason: liquibase.exception.DatabaseException: ERROR: relation "credential" already exists [Failed SQL: (0) CREATE TABLE public.credential (id BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, login VARCHAR(32) NOT
NULL, experience BIGINT NOT NULL, email VARCHAR(128) NOT NULL, password VARCHAR(255) NOT NULL, role VARCHAR(32) NOT NULL, file_name VARCHAR(1024), CONSTRAINT CREDENTIAL_PKEY PRIMARY KEY (id), UNIQUE (login))]
dexterity |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5.3.6.jar!/:5.3.6]
dexterity |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) ~[spring-beans-5.3.6.jar!/:5.3.6]
dexterity |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.6.jar!/:5.3.6]
dexterity |     at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.6.jar!/:5.3.6]
dexterity |     at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.6.jar!/:5.3.6]
dexterity |     at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.6.jar!/:5.3.6]
dexterity |     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.6.jar!/:5.3.6]
dexterity |     at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.3.6.jar!/:5.3.6]
dexterity |     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.6.jar!/:5.3.6]
dexterity |     at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.6.jar!/:5.3.6]
dexterity |     at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.6.jar!/:5.3.6]
dexterity |     at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.6.jar!/:5.3.6]
dexterity |     at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144) ~[spring-boot-2.4.5.jar!/:2.4.5]
dexterity |     at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:782) ~[spring-boot-2.4.5.jar!/:2.4.5]
dexterity |     at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:774) ~[spring-boot-2.4.5.jar!/:2.4.5]
dexterity |     at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:439) ~[spring-boot-2.4.5.jar!/:2.4.5]
dexterity |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:339) ~[spring-boot-2.4.5.jar!/:2.4.5]
dexterity |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:1340) ~[spring-boot-2.4.5.jar!/:2.4.5]
dexterity |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:1329) ~[spring-boot-2.4.5.jar!/:2.4.5]
dexterity |     at ru.dexterity.DexterityApplication.main(DexterityApplication.java:13) ~[classes!/:2.4.5]
dexterity |     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
dexterity |     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
dexterity |     at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
dexterity |     at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
dexterity |     at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[dexterity.jar:2.4.5]
dexterity |     at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) ~[dexterity.jar:2.4.5]
dexterity |     at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[dexterity.jar:2.4.5]
dexterity |     at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88) ~[dexterity.jar:2.4.5]
dexterity | Caused by: liquibase.exception.MigrationFailedException: Migration failed for change set classpath:db/changelog/db.changelog-master.yaml::1::ulxanxv:
dexterity |      Reason: liquibase.exception.DatabaseException: ERROR: relation "credential" already exists [Failed SQL: (0) CREATE TABLE public.credential (id BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, login VARCHAR(32) NOT
NULL, experience BIGINT NOT NULL, email VARCHAR(128) NOT NULL, password VARCHAR(255) NOT NULL, role VARCHAR(32) NOT NULL, file_name VARCHAR(1024), CONSTRAINT CREDENTIAL_PKEY PRIMARY KEY (id), UNIQUE (login))]
dexterity |     at liquibase.changelog.ChangeSet.execute(ChangeSet.java:659) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     at liquibase.changelog.visitor.UpdateVisitor.visit(UpdateVisitor.java:53) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     at liquibase.changelog.ChangeLogIterator.run(ChangeLogIterator.java:97) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     at liquibase.Liquibase.update(Liquibase.java:201) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     at liquibase.Liquibase.update(Liquibase.java:178) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     at liquibase.integration.spring.SpringLiquibase.performUpdate(SpringLiquibase.java:368) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:316) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1845) ~[spring-beans-5.3.6.jar!/:5.3.6]
dexterity |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782) ~[spring-beans-5.3.6.jar!/:5.3.6]
dexterity |     ... 27 common frames omitted
dexterity | Caused by: liquibase.exception.DatabaseException: ERROR: relation "credential" already exists [Failed SQL: (0) CREATE TABLE public.credential (id BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, login VARCHAR(32) NOT NU
LL, experience BIGINT NOT NULL, email VARCHAR(128) NOT NULL, password VARCHAR(255) NOT NULL, role VARCHAR(32) NOT NULL, file_name VARCHAR(1024), CONSTRAINT CREDENTIAL_PKEY PRIMARY KEY (id), UNIQUE (login))]
dexterity |     at liquibase.executor.jvm.JdbcExecutor$ExecuteStatementCallback.doInStatement(JdbcExecutor.java:430) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:87) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:159) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     at liquibase.database.AbstractJdbcDatabase.execute(AbstractJdbcDatabase.java:1276) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     at liquibase.database.AbstractJdbcDatabase.executeStatements(AbstractJdbcDatabase.java:1258) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     at liquibase.changelog.ChangeSet.execute(ChangeSet.java:622) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     ... 35 common frames omitted
dexterity | Caused by: org.postgresql.util.PSQLException: ERROR: relation "credential" already exists
dexterity |     at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2553) ~[postgresql-42.2.19.jar!/:42.2.19]
dexterity |     at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2285) ~[postgresql-42.2.19.jar!/:42.2.19]
dexterity |     at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:323) ~[postgresql-42.2.19.jar!/:42.2.19]
dexterity |     at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:481) ~[postgresql-42.2.19.jar!/:42.2.19]
dexterity |     at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:401) ~[postgresql-42.2.19.jar!/:42.2.19]
dexterity |     at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:322) ~[postgresql-42.2.19.jar!/:42.2.19]
dexterity |     at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:308) ~[postgresql-42.2.19.jar!/:42.2.19]
dexterity |     at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:284) ~[postgresql-42.2.19.jar!/:42.2.19]
dexterity |     at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:279) ~[postgresql-42.2.19.jar!/:42.2.19]
dexterity |     at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95) ~[HikariCP-3.4.5.jar!/:na]
dexterity |     at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-3.4.5.jar!/:na]
dexterity |     at liquibase.executor.jvm.JdbcExecutor$ExecuteStatementCallback.doInStatement(JdbcExecutor.java:426) ~[liquibase-core-3.10.3.jar!/:na]
dexterity |     ... 40 common frames omitted

Вот мои файлы с настройками:

application.yml

spring:
## PostgreSQL
  datasource:
    url: jdbc:postgresql://localhost:5432/dexterity
    username: postgres
    password: 1234
    driver-class-name: org.postgresql.Driver
## Web
  web:
    resources:
      cache:
        cachecontrol:
          no-cache: true
  thymeleaf:
    cache: false
  jpa:
    hibernate:
      ddl-auto: none

## Liquibase
  liquibase:
    enabled: true
    change-log: classpath:db/changelog/db.changelog-master.yaml

## Server
server:
  port: 8080
  error:
    whitelabel:
      enabled: false

## Properties
upload:
  images-path: src/main/resources/static/images/
  resources-path: src\main\resources\static\images

compileta:
  compileUrl: http://localhost:8081/compile
  compileAllUrl: http://localhost:8081/compile_all

db.changelog-master.yaml

databaseChangeLog:
  - changeSet:
      id: 1
      author: ulxanxv
      changes:
        - createTable:
            tableName: credential
            columns:
              - column:
                  name: id
                  type: bigint
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: login
                  type: varchar(32)
                  constraints:
                    unique: true
                    nullable: false
              - column:
                  name: experience
                  type: bigint
                  constraints:
                    unique: false
                    nullable: false
              - column:
                  name: email
                  type: varchar(128)
                  constraints:
                    nullable: false
              - column:
                  name: password
                  type: varchar(255)
                  constraints:
                    nullable: false
              - column:
                  name: role
                  type: varchar(32)
                  constraints:
                    nullable: false
              - column:
                  name: file_name
                  type: varchar(1024)
                  constraints:
                    nullable: true
        - createTable:
            tableName: task
            columns:
              - column:
                  name: id
                  type: bigint
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: in_moderation
                  type: boolean
                  constraints:
                    nullable: false
              - column:
                  name: short_description
                  type: varchar(128)
                  constraints:
                    unique: true
                    nullable: false
              - column:
                  name: long_description
                  type: varchar(32768)
                  constraints:
                    nullable: false
              - column:
                  name: class_name
                  type: varchar(256)
              - column:
                  name: test_class_name
                  type: varchar(256)
              - column:
                  name: test_code
                  type: varchar(32768)
                  constraints:
                    nullable: false
              - column:
                  name: start_code
                  type: varchar(32768)
                  constraints:
                    nullable: false
              - column:
                  name: difficult
                  type: int
                  constraints:
                    nullable: false
        - createTable:
            tableName: task_rating
            columns:
              - column:
                  name: id
                  type: bigint
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: credential_id
                  type: bigint
                  constraints:
                    foreignKeyName: FK_credential_id
                    references: credential(id)
                    nullable: false
              - column:
                  name: task_id
                  type: bigint
                  constraints:
                    foreignKeyName: FK_task_rating_task
                    references: task(id)
                    nullable: false
              - column:
                  name: solution
                  type: varchar(32768)
                  constraints:
                    nullable: false
              - column:
                  name: brevity
                  type: bigint
                  constraints:
                    nullable: false
              - column:
                  name: rapidity
                  type: double
                  constraints:
                    nullable: false
              - column:
                  name: total_score
                  type: double
                  constraints:
                    nullable: false
        - addUniqueConstraint:
            columnNames: credential_id, task_id
            constraintName: UNIQUE_TASK_RATING_credential_id_task_id
            tableName: task_rating

docker-compose.yml

version: '3.7'

services:

  app:
    container_name: dexterity
    build: .
    ports:
      - 8080:8080
    command: java -jar --spring.profiles.active=dev dexterity.jar
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/dexterity
      SPRING_DATASOURCE_USERNAME: postgres
      SPRING_DATASOURCE_PASSWORD: 1234
      SPRING_JPA_HIBERNATE_DDL_AUTO: none
    links:
      - db

  db:
    container_name: postgres
    image: postgres:latest
    ports:
      - 5432:5432
    volumes:
      - ./pg_data:/var/lib/postgresql/data/pgdata
    environment:
      POSTGRES_USERNAME: postgres
      POSTGRES_PASSWORD: 1234
      POSTGRES_DB: dexterity
4
  • Добавил Dockerfile, а разве он участвует при создании, если я использую docker-compose? Просто я только начинаю разбираться с Docker — очень много чего не знаю) Не очень понял про команду запуска, я запускаю просто docker-compose up и больше ничего
    – ulxanxv
    10 мая 2021 в 7:51
  • Спасибо, разобрался) Оказывается он действительно их создал, но не мог подключиться по неизвестной мне причине) Достаточно было просто к запустить отдельно бд и удалить вручную, чтобы он их пересоздал
    – ulxanxv
    10 мая 2021 в 8:17
  • А ещё один вопрос, может сможешь чем то подсказать. У меня мой проект взаимодействует с папкой images, которая располагается в resources. После запуска проекта в Docker он перестает видеть любые файлы, которые там находятся. Как можно правильно поступить в такой ситуации? Путь до папки относительно корня — src\main\resources\static\images, а сам путь в HTML-файле указываю так — /images/anon.jpg, к примеру
    – ulxanxv
    10 мая 2021 в 8:24
  • Это нужно задать новый вопрос и описать там детали. В комментариях и неудобно уточнять детали и неправильно. 10 мая 2021 в 11:33

2 ответа 2

1

У вас проблема не в том, что liquibase "не хочет" создавать таблицу, а в том что хочет, но таблица уже создана.

Т.е. в БД, на которую вы направили ваше приложение (и compose видно, что это локальная папка pg_data), уже создана таблица credential, но, очевидно, в обход liquibase. liquibase хранит в БД, какие миграции уже запускались, чтобы заново их не запускать. В это БД этой информации нет.

Возможно вы таблицу сами вручную создали в процессе разработки. Используйте другую БД в docker, или удалите таблицы из той, которую вы докеру указали.

0

Таблицы созданы вне liquibase:

ERROR: relation "credential" already exists [Failed SQL: (0)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.