如何使我的Docker容器与我的本地PostgreSQL数据库进行通信?

huangapple go评论66阅读模式
英文:

How can I get my Docker container to communicate with my locale Postgresql database?

问题

我知道我的问题很常见,所有问题都已经得到解答,但是我在构建一个带有Spring Boot应用程序的Docker容器时遇到了问题,已经四天了仍然无法前进。
我有一个本地的Postgresql数据库,我想要用我的容器访问它。然而,我总是收到以下错误:
org.postgresql.util.PSQLException: 拒绝连接到localhost:5432。请检查主机名和端口是否正确,并且postmaster是否接受TCP/IP连接。

我已经在YouTube上观看了每一个视频,和我的朋友"Chat..."一起,我也一直在徒劳地尝试。

这是我的application.properties

server.port=8080

## 数据库配置
spring.datasource.url= jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=admin

spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.default_schema=invdr-webshop
# 格式化SQL
spring.jpa.properties.hibernate.format_sql=true
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
# 取消注释以显示SQL
spring.jpa.properties.hibernate.show_sql=true
# 显示绑定参数
logging.level.org.hibernate.type.descriptor.sql=DEBUG

allowed.origins=http://localhost:4200
spring.data.rest.base-path=/api

这是我的Dockerfile:

FROM openjdk:17.0.2-jdk-slim
# 在容器中设置工作目录
WORKDIR /app

# 将Spring Boot JAR复制到容器中
COPY target/webshop-0.0.1-SNAPSHOT.jar app.jar

ENTRYPOINT ["java","-jar", "app.jar"]

EXPOSE 8080

当我启动JAR文件时,我没有收到错误消息,一切都运行正常。数据库连接也经过了1000次的测试,它可以工作。

使用以下命令:

docker build -t test .

我创建了我的Docker镜像,
然后使用

docker run --network=test:latest  

来启动容器。在这里,我告诉容器它可以与外界通信。

以下是我的Postgres设置:

# - 连接设置 -

listen_addresses = ' * '		# 要监听的IP地址(es);
					# 逗号分隔的地址列表;
					# 默认为'localhost'; 使用'*'表示全部
					# (更改需要重新启动)
port = 5432				# (更改需要重新启动)
max_connections = 100			# (更改需要重新启动)
#superuser_reserved_connections = 3	# (更改需要重新启动)
#unix_socket_directories = ''	# 逗号分隔的目录列表

我还检查了我的防火墙。在防火墙设置中,我找到了Docker Desktop Backend的应用程序,并且它既可以在私人环境中访问,也可以在公共环境中访问。这足够吗?

docker network inspect bridge
[
    {
        "Name": "bridge",
        "Id": "fccdfe4adbdd4d9fd24cbca4c221410f1a9684e00ec6dba6fb034e2bfae1c1b7",
        "Created": "2023-07-06T13:12:54.8598131Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]

我尝试在另一台机器上运行容器,但没有成功。

有人可以告诉我如何摆脱我的绝望,以及错误在哪里吗?提前感谢。

英文:

I know that my problem is an old shoe and this topic has already been answered in all questions but however I am running into a problem building a Docker container with a Spring Boot Application and just can't get ahead since 4 days.
I have a local Postgresql database that I want to access with my container. However, I always get the error:
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

I went through every video on Youtube and with my friend "Chat..." I'm also just going around in circles.

This is my application.properties

server.port=8080

## Database konfiguration
spring.datasource.url= jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=admin

spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.default_schema=invdr-webshop
# pretty format SQL
spring.jpa.properties.hibernate.format_sql=true
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
# uncomment to show sql
spring.jpa.properties.hibernate.show_sql=true
# show bind parameters
logging.level.org.hibernate.type.descriptor.sql=DEBUG

allowed.origins=http://localhost:4200
spring.data.rest.base-path=/api

here is my Dockerfile:

FROM openjdk:17.0.2-jdk-slim
# Setzen der Arbeitsverzeichnis im Container
WORKDIR /app

# Kopieren des Spring Boot-JARs in den Container
COPY target/webshop-0.0.1-SNAPSHOT.jar app.jar

ENTRYPOINT ["java","-jar", "app.jar"]

EXPOSE 8080

When I start the jar I get no errors and everything works great. The database connection was also tested for the 1000th time and it works.

When I start the jar I get no errors and everything works great. The database connection was also tested for the 1000th time and it works.

With the command:

docker build -t test .

I create my Docker image
and with

docker run --network=test:latest  

I start the container. Here I tell the container that it can communicate with the outside world.

Here are my Postgres Settings

# - Connection Settings -

listen_addresses = '*'		# what IP address(es) to listen on;
					# comma-separated list of addresses;
					# defaults to 'localhost'; use '*' for all
					# (change requires restart)
port = 5432				# (change requires restart)
max_connections = 100			# (change requires restart)
#superuser_reserved_connections = 3	# (change requires restart)
#unix_socket_directories = ''	# comma-separated list of directories

I have also checked my firewall. In the firewall settings I find the app Docker Desktop Backend under "Allowed Apps and Features" and it is accessible both privately and publicly. Is this sufficient?

 docker network inspect bridge
[
    {
        "Name": "bridge",
        "Id": "fccdfe4adbdd4d9fd24cbca4c221410f1a9684e00ec6dba6fb034e2bfae1c1b7",
        "Created": "2023-07-06T13:12:54.8598131Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]

I have tried to run the container on another machine but without success.

Can someone tell me how to get out of my despair and where the error lies? Thanks in advance

答案1

得分: 1

以下是您要翻译的内容:

"对于容器来说,本地主机是未知的,可以尝试使用 IP 或主机名:"

spring.datasource.url= jdbc:postgresql://<IP 或 NAME 即 pgdb>:5432/postgres

重新运行应用程序。如果错误消息发生变化,请在问题上进行更新。

问题:似乎您没有一个包含 PostgreSQL 服务的 Docker Compose 文件?

更新:

构建您当前的 Docker 文件并打标签(删除 EXPOSE 语句):

应用程序的 Docker 文件:

FROM openjdk:17.0.2-jdk-slim

设置容器中的工作目录

WORKDIR /app

将 Spring Boot JAR 复制到容器中

COPY target/webshop-0.0.1-SNAPSHOT.jar app.jar

ENTRYPOINT ["java","-jar", "app.jar"]

docker build -f <上述 Docker 文件的名称> -t app/app:latest .

现在创建一个 Docker Compose 文件如下:

version: "3"
services:
app:
build: .
container_name: <上述提供的名称>
environment:
SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/postgres
ports:

  • 8000:8080
    restart: always
    depends_on:
  • db
    db:
    image: postgres
    container_name: db
    environment:
  • POSTGRES_USER=<用户>
  • POSTGRES_PASSWORD=<密码>
  • POSTGRES_DB=<数据库名称>
  • PGDATA=/var/lib/postgresql/data/pgdata
    ports:
  • 5000:5432
    volumes:
  • pgdata:/var/lib/postgresql/data
    restart: always
    volumes:
    pgdata:

请注意,在数据源上使用的名称,您可以在 localhost 和服务名称(db)之间切换。

英文:

For a container localhost is something unknown, either try with IP or hostname here:

 spring.datasource.url= jdbc:postgresql://&lt;IP or NAME ie pgdb&gt;:5432/postgres

Re run the app. If error message changes please make an update on the question.

Question: seems that you do not have a dockercompose file with a service for postgres ?

UPDATE:

build your current docker file and tag it (REMOVE the EXPOSE statement):

Docker file for app:

FROM openjdk:17.0.2-jdk-slim
# Setzen der Arbeitsverzeichnis im Container
WORKDIR /app

# Kopieren des Spring Boot-JARs in den Container
COPY target/webshop-0.0.1-SNAPSHOT.jar app.jar

ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;, &quot;app.jar&quot;]

docker build -f <Name of Docker file Above> -t app/app:latest .

Now create a docker compose as follows:

  version: &quot;3&quot;
  services:
    app:
      build: .
      container_name: &lt;NAME PROVIDED ABOVE&gt;
      environment:
        SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/postgres
      ports:
        - 8000:8080
      restart: always
      depends_on:
        - db
    db:
      image: postgres
      container_name: db
      environment:
        - POSTGRES_USER=&lt;USER&gt;
        - POSTGRES_PASSWORD=&lt;PASS&gt;
        - POSTGRES_DB=&lt;DBNAME&gt;
        - PGDATA=/var/lib/postgresql/data/pgdata
      ports:
        - 5000:5432
      volumes:
        - pgdata:/var/lib/postgresql/data
      restart: always
  volumes:
    pgdata:

Notice the name used on the datasource you can switch between localhost and service name (db)

huangapple
  • 本文由 发表于 2023年7月7日 00:42:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76630941.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定