简体   繁体   English

无法连接到在 docker 中运行的 postgres

[英]Can't connect to postgres running in docker

I started the Postgres in Docker.我在 Docker 中启动了 Postgres。 It works fine.它工作正常。 I wend inside docker container through bash and checked that DB is working.我通过 bash 进入 docker 容器并检查数据库是否正常工作。 The goal is to connect it with an app spring mvc without spring boot.目标是在没有 spring 引导的情况下将其与应用程序 spring mvc 连接起来。 If I understood correctly, the problem lies with connection with Postgres.如果我理解正确,问题在于与 Postgres 的连接。 The app can't connect to id.该应用程序无法连接到 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. 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:标准 Docker 文件:

FROM postgres

ENV POSTGRES_USER task1
ENV POSTGRES_PASSWORD task1
ENV POSTGRES_DB users

and docker-compose:和 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:来自 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

The problem is in you docker-compose.yml file.问题出在您的 docker-compose.yml 文件中。 You need to map the database port.您需要 map 数据库端口。 Change the ports from 6000:6000 to 6000:5432 and then docker-compose down and docker-compose up .将端口从6000:6000更改为6000:5432 ,然后将docker-compose downdocker-compose up

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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