简体   繁体   中英

Can't access spring boot app running inside docker container from localhost

I've been struggling for a couple of hours on this issue. I have the following setup:

Dockerfile

FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/ROOT.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","app.jar","--spring.profiles.active=dev"]
EXPOSE 8080

docker-compose.yml

version: '3'
services:
  app:
      container_name: app
      build:
         context: .
         dockerfile: Dockerfile
      restart: always
      links:
        - mysql-db
      depends_on:
        - mysql-db
      ports:
        - 8080:8080
      expose:
        - 8080
      networks:
        - spring-network
  mysql-db:
      restart: always
      container_name: mysql_db
      image: "mysql:8.0.19" 
      ports:
        - 3306:3306
      networks:
        - spring-network
      environment:
         MYSQL_ROOT_PASSWORD: 'password'
         MYSQL_DATABASE: 'db'
         MYSQL_USER: 'db-user'
         MYSQL_PASSWORD: 'password'
      volumes:
        - mysql-db:/var/lib/mysql
      command: --innodb-use-native-aio=0
      security_opt:
        - seccomp:unconfined
volumes:
  mysql-db:
networks:
    spring-network:
        driver: bridge

when I run the app using docker-compose up it works fine inside the container, but when I hit localhost:8080 on the browser I got

localhost unexpectedly closed the connection

Edit:

  • spring boot app running on port 8080
  • docker version 19.03.8

After a few days, I figured out what was the issue. I was using an old jar file (which exposes the application on port 80:/ ), all I did is generating a new build which exposes the app on 8080 mvn clean install then build the image docker-compose build and everything works fine now

Remove expose - it's for internal use between containers

Documentation for expose

Edit: You also have a brided network and you can only communicate between containers on the same bridged network as default.

Either just remove the network parts - this could cause containers being too exposed if this is a problem.

Or read about port forwarding here

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