Docker 容器在没有端口映射的情况下运行

时间:2021-04-20 10:51:28

标签: docker docker-compose dockerfile

我创建了一个 docker-compose 文件来从 dockerfile 构建图像,然后运行容器,这是我的代码:

Dockerfile

FROM anapsix/alpine-java

VOLUME [ "/var/run/jars/" ]

ADD hello-world.jar /var/run/jars/

EXPOSE 8080
ENTRYPOINT [ "java" ]
CMD ["-?"]

docker-compose.yml

version: '3'
services:
  hello-world-image:
   build: .
   image: hello-world-image    
  hello-world:
   image: hello-world-image
   container_name: hello-world
   ports:
    - "8080:8080"
   volumes:
     - ./logs_ACM:/root/logs_ACM
   command: -jar /var/run/jars/hello-world.jar
   restart: always

docker ps 输出:

CONTAINER ID   IMAGE               COMMAND                  CREATED         STATUS                                  PORTS     NAMES
103b0a3c30e3   hello-world-image   "java -jar /var/run/…"   5 seconds ago   Restarting (1) Less than a second ago             hello-world

当我使用“docker ps”检查正在运行的容器时,端口列是空的,因此即使我在我的 docker compose 文件中指定了端口,也没有完成端口映射。 需要对我的 docker-compose 文件进行哪些更改才能解决此问题?

新版本的 dockerfile 和 docker-compose :

FROM anapsix/alpine-java

USER root

RUN mkdir -p /var/run/jars/

COPY spring-petclinic-2.4.2.jar /var/run/jars/

EXPOSE 8081

ENTRYPOINT [ "java" ]

CMD ["-?"]

version: '3'  # '3' means '3.0'
services:
spring-petclinic:
 build: .
# Only if you're planning to `docker-compose push`
# image: registry.example.com/name/hello-world-image:${TAG:-latest}
 ports:
  - "8081:8081"
 volumes:
 # A bind-mount directory to read out log files is a good use of
 # `volumes:`.  This does not require special setup in the Dockerfile.
  - ./logs_ACM:/root/logs_ACM
 command: -jar /var/run/jars/spring-petclinic-2.4.2.jar
mysql:
 image: mysql:5.7
 ports:
  - "3306:3306"
 environment:
  - MYSQL_ROOT_PASSWORD=
  - MYSQL_ALLOW_EMPTY_PASSWORD=true
  - MYSQL_USER=petclinic
  - MYSQL_PASSWORD=petclinic
  - MYSQL_DATABASE=petclinic
 volumes:
  - "./conf.d:/etc/mysql/conf.d:ro"

1 个答案:

答案 0 :(得分:1)

我认为您最大的问题是 Dockerfile 中的 VOLUME 指令。 https://docs.npmjs.com/cli/run-script 注释:

<块引用>

从 Dockerfile 中更改卷:如果任何构建步骤在声明后更改了卷中的数据,这些更改将被丢弃。

因此,当您为包含 jar 文件的目录声明一个 VOLUME,然后尝试向其中添加 ADD 内容时,它会丢失。

在大多数实际情况下,您不需要 VOLUME。您应该能够将 Dockerfile 重写为:

FROM anapsix/alpine-java

# Do not create a VOLUME.

# Generally prefer COPY to ADD.  Will create the target directory if needed.
COPY hello-world.jar /var/run/jars/

EXPOSE 8080

# Don't set an ENTRYPOINT just naming an interpreter.
# Do make the default container command be to run the application.
CMD ["java", "-jar", "/var/run/jars/hello-world.jar"]

docker-compose.yml 文件中,您不需要单独的“服务”来构建映像,并且您通常不需要覆盖 container_name:(由 Compose 提供)或 {{ 1}}(来自 Dockerfile)。这可以简化为:

command:
相关问题