简体   繁体   中英

Can't connect to postgres running in docker

I started the Postgres in Docker. It works fine. I wend inside docker container through bash and checked that DB is working. The goal is to connect it with an app spring mvc without spring boot. If I understood correctly, the problem lies with connection with Postgres. The app can't connect to id. How to fix it? The app builds and starts correctly. Get request works fine, but when I try to post it hasn't worked.

I have tried to use two different datasource: If I do post I see the error in browser:

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

The error is:

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

This error I see in console when the app is starting:

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.

Standart Docker file:

FROM postgres

ENV POSTGRES_USER task1
ENV POSTGRES_PASSWORD task1
ENV POSTGRES_DB users

and docker-compose:

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

Other code:

@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 {}

logs from docker container:

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

The problem is in you docker-compose.yml file. You need to map the database port. Change the ports from 6000:6000 to 6000:5432 and then docker-compose down and docker-compose up .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM