簡體   English   中英

無法連接到在 docker 中運行的 postgres

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

我在 Docker 中啟動了 Postgres。 它工作正常。 我通過 bash 進入 docker 容器並檢查數據庫是否正常工作。 目標是在沒有 spring 引導的情況下將其與應用程序 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

問題出在您的 docker-compose.yml 文件中。 您需要 map 數據庫端口。 將端口從6000:6000更改為6000:5432 ,然后將docker-compose downdocker-compose up

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM