无法连接到在Docker中运行的Postgres

时间:2020-04-17 16:58:47

标签: postgresql hibernate docker spring-mvc spring-data

我在Docker中启动了Postgres。它工作正常。我通过bash将其放入docker容器中,并检查DB是否正常工作。 目标是将其与没有spring boot的app spring mvc连接。 如果我理解正确,则问题出在与Postgres的连接上。 该应用程序无法连接到ID。如何解决? 该应用会生成并正确启动。获取请求的效果很好,但是当我尝试发布时却没有效果。

我尝试使用两个不同的数据源: 如果我发帖,我会在浏览器中看到错误:

1。

@Bean
public DataSource dataSource() {
    DriverManagerDataSource driver = new DriverManagerDataSource();
    driver.setDriverClassName("org.postgresql.Driver");
    driver.setUrl("jdbc:postgresql://localhost:6000/users");
    driver.setUsername("postgres");
    driver.setPassword("task1");
    return driver;
}

错误是:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
  1. @Bean
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource driver = new ComboPooledDataSource();
        driver.setDriverClass("org.postgresql.Driver");
        driver.setJdbcUrl("jdbc:postgresql://localhost:6000/users");
        driver.setUser("postgres");
        driver.setPassword("task1");
        return driver;
    }
    

启动应用程序时,我在控制台中看到此错误:

17-Apr-2020 19:26:58.016 WARNING [C3P0PooledConnectionPoolManager[identityToken->z8kfsxa912030ejmgd6af|6144d891]-HelperThread-#2] com.mchange.v2.resourcepool.BasicResourcePool. Having failed to acquire a resource, com.mchange.v2.resourcepool.BasicResourcePool@46e95772 is interrupting all Threads waiting on a resource to check out. Will try again in response to new client requests.
17-Apr-2020 19:26:58.011 WARNING [C3P0PooledConnectionPoolManager[identityToken->z8kfsxa912030ejmgd6af|6144d891]-HelperThread-#1] com.mchange.v2.resourcepool.BasicResourcePool. com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@628b9aa1 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: 
    org.postgresql.util.PSQLException: The connection attempt failed.

标准Docker文件:

FROM postgres

ENV POSTGRES_USER task1
ENV POSTGRES_PASSWORD task1
ENV POSTGRES_DB users

和docker-compose:

version: "3.7"
services:
  postgres:
    build:
      context: .
      dockerfile: db.Dockerfile
    image: postgrei
    container_name: DB
    ports:
    - 6000:6000

其他代码:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("com.repository")
@ComponentScan(basePackages = "com.task1")
public class DataJpaConfig {



    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource driver = new ComboPooledDataSource();
        driver.setDriverClass("org.postgresql.Driver");
        driver.setJdbcUrl("jdbc:postgresql://localhost:6000/users");
        driver.setUser("postgres");
        driver.setPassword("task1");
        return driver;
    }


    @Bean
    public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
        final JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        return new HibernateJpaVendorAdapter();
    }

    @Bean
    public Properties hibernateProperties() {
        Properties hibernateProp = new Properties();
        hibernateProp.put("hibernate.dialect",
                "org.hibernate.dialect.PostgreSQL95Dialect");
        hibernateProp.put("hibernate.format sql", true);
        hibernateProp.put("hibernate.use sql comments", true);
        hibernateProp.put("hibernate.show_sql", true);
        hibernateProp.put("hibernate.max_fetch_depth", 3);
        hibernateProp.put("hibernate.jdbc.batch_size", 10);
        hibernateProp.put("hibernate.jdbc.fetch_size", 50);
        return hibernateProp;
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean factoryBean =
        new LocalContainerEntityManagerFactoryBean();
        factoryBean.setPackagesToScan(
                "com.task1");
        try {
            factoryBean.setDataSource(dataSource());
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        factoryBean.setJpaVendorAdapter(
                new HibernateJpaVendorAdapter());
        factoryBean.setJpaProperties(hibernateProperties());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
        factoryBean.afterPropertiesSet();
        return factoryBean.getNativeEntityManagerFactory();
    }

}


public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{DataJpaConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{ApplicationConfiguration.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}


@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan(basePackages = "com.task1")
public class ApplicationConfiguration implements WebMvcConfigurer {}

来自docker容器的日志:

The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.utf8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

fixing permissions on existing directory /var/lib/postgresql/data ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default time zone ... Etc/UTC
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok


Success. You can now start the database server using:

    pg_ctl -D /var/lib/postgresql/data -l logfile start

initdb: warning: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.
waiting for server to start....2020-04-17 16:17:52.683 UTC [47] LOG:  starting PostgreSQL 12.2 (Debian 12.2-2.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
2020-04-17 16:17:52.684 UTC [47] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2020-04-17 16:17:52.698 UTC [48] LOG:  database system was shut down at 2020-04-17 16:17:50 UTC
2020-04-17 16:17:52.702 UTC [47] LOG:  database system is ready to accept connections
 done
server started
CREATE DATABASE


/usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/createUserTable.sql
CREATE TABLE


/usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/putDataToUserTable.sql
INSERT 0 3


waiting for server to shut down...2020-04-17 16:17:53.317 UTC [47] LOG:  received fast shutdown request
.2020-04-17 16:17:53.332 UTC [47] LOG:  aborting any active transactions
2020-04-17 16:17:53.335 UTC [47] LOG:  background worker "logical replication launcher" (PID 54) exited with exit code 1
2020-04-17 16:17:53.335 UTC [49] LOG:  shutting down
2020-04-17 16:17:53.407 UTC [47] LOG:  database system is shut down
 done
server stopped

PostgreSQL init process complete; ready for start up.

2020-04-17 16:17:53.431 UTC [1] LOG:  starting PostgreSQL 12.2 (Debian 12.2-2.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
2020-04-17 16:17:53.432 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
2020-04-17 16:17:53.432 UTC [1] LOG:  listening on IPv6 address "::", port 5432
2020-04-17 16:17:53.441 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2020-04-17 16:17:53.454 UTC [83] LOG:  database system was shut down at 2020-04-17 16:17:53 UTC
2020-04-17 16:17:53.458 UTC [1] LOG:  database system is ready to accept connections

1 个答案:

答案 0 :(得分:1)

问题出在您的docker-compose.yml文件中。 您需要映射数据库端口。 将端口从6000:6000更改为6000:5432,然后将docker-compose downdocker-compose up更改。