JAVA项目发布到docker

本文介绍如何在CentOS 7上配置Docker的远程API,包括打开2375端口、重启docker服务验证配置成功及创建Spring Boot项目并使用docker-maven-plugin。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步:打开docker远程API端口

​ 我的是centos7系统,需要修改的文件是/usr/lib/systemd/system/docker.service 文件

vim /usr/lib/systemd/system/docker.service 

如下是我的配置文件,需要添加的部分是在第13-17行:ExecStart=/usr/bin/dockerd的后面加上-H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock,ok之后 :wq ,保存并退出。注意的是0.0.0.0,你没看错,这样配置就行,并不是自己的主机ip

[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target firewalld.service
Wants=network-online.target

[Service]
Type=notify
# the default is not to use systemd for cgroups because the delegate issues still
# exists and systemd currently does not support the cgroup feature set required
# for containers run by docker

#start add config

ExecStart=/usr/bin/dockerd  -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock

#end
ExecReload=/bin/kill -s HUP $MAINPID
# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
# Uncomment TasksMax if your systemd version supports it.
# Only systemd 226 and above support this version.
#TasksMax=infinity
TimeoutStartSec=0
# set delegate yes so that systemd does not reset the cgroups of docker containers
Delegate=yes
# kill only the docker process, not all processes in the cgroup
KillMode=process
# restart the docker process if it exits prematurely
Restart=on-failure
StartLimitBurst=3
StartLimitInterval=60s

[Install]
WantedBy=multi-user.target

第二步:重启docker的守护进程,重启docker

命令如下:

systemctl daemon-reload

systemctl restart docker

输入netstat -anp|grep 2375 显示docker正在监听2375端口

[root@izjmd5lqoeeowpz ~]# netstat -anp|grep 2375
tcp6       0      0 :::2375                 :::*                    LISTEN      2577/dockerd

输入curl 127.0.0.1:2375/info 显示一大堆信息,证明端口已经对外开放了

{"ID":"5ZCY:OFMV:ZO4J:WMQ2:OW57:76PX:VSF2:YX6W:6NKU:3YK6:5WJX:P7BT","Containers":0,"ContainersRunning":0,"ContainersPaused":0,"ContainersStopped":0,"Images":0,"Driver":"overlay2","DriverStatus":[["Backing Filesystem","extfs"],["Supports d_type","true"],["Native Overlay Diff","false"]],"SystemStatus":null,"Plugins":{"Volume":["local"],"Network":["bridge","host","macvlan","null","overlay"],"Authorization":null,"Log":["awslogs","fluentd","gcplogs","gelf","journald","json-file","logentries","splunk","syslog"]},"MemoryLimit":true,"SwapLimit":true,"KernelMemory":true,"CpuCfsPeriod":true,"CpuCfsQuota":true,"CPUShares":true,"CPUSet":true,"IPv4Forwarding":true,"BridgeNfIptables":true,"BridgeNfIp6tables":true,"Debug":false,"NFd":24,"OomKillDisable":true,"NGoroutines":44,"SystemTime":"2018-10-01T16:31:00.417378358+08:00","LoggingDriver":"json-file","CgroupDriver":"cgroupfs","NEventsListener":0,"KernelVersion":"3.10.0-514.26.2.el7.x86_64","OperatingSystem":"CentOS Linux 7 (Core)","OSType":"linux","Architecture":"x86_64","IndexServerAddress":"https://index.docker.io/v1/","RegistryConfig":{"AllowNondistributableArtifactsCIDRs":[],"AllowNondistributableArtifactsHostnames":[],"InsecureRegistryCIDRs":["127.0.0.0/8"],"IndexConfigs":{"docker.io":{"Name":"docker.io","Mirrors":[],"Secure":true,"Official":true}},"Mirrors":[]},"NCPU":1,"MemTotal":1928933376,"GenericResources":null,"DockerRootDir":"/var/lib/docker","HttpProxy":"","HttpsProxy":"","NoProxy":"","Name":"izjmd5lqoeeowpz","Labels":[],"ExperimentalBuild":false,"ServerVersion":"18.06.1-ce","ClusterStore":"","ClusterAdvertise":"","Runtimes":{"runc":{"path":"docker-runc"}},"DefaultRuntime":"runc","Swarm":{"NodeID":"","NodeAddr":"","LocalNodeState":"inactive","ControlAvailable":false,"Error":"","RemoteManagers":null},"LiveRestoreEnabled":false,"Isolation":"","InitBinary":"docker-init","ContainerdCommit":{"ID":"468a545b9edcd5932818eb9de8e72413e616e86e","Expected":"468a545b9edcd5932818eb9de8e72413e616e86e"},"RuncCommit":{"ID":"69663f0bd4b60df09991c08812a60108003fa340","Expected":"69663f0bd4b60df09991c08812a60108003fa340"},"InitCommit":{"ID":"fec3683","Expected":"fec3683"},"SecurityOptions":["name=seccomp,profile=default"]}

第三步:创建一个springboot项目

start.spring.io

第四步: 添加插件docker-maven-plugin

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>1.0.0</version>
    <configuration>
        <imageName>${docker.image.prefix}-${project.artifactId}</imageName>
        <!--<dockerDirectory>src/main/docker</dockerDirectory>-->
        <baseImage>java</baseImage>
        <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
        <resources>
            <resource>
                <targetPath>/</targetPath>
                <directory>${project.build.directory}</directory>
                <include>${project.build.finalName}.jar</include>
            </resource>
        </resources>
    </configuration>
</plugin>
### 如何在 Docker 中安装并部署 Java 项目 #### 准备工作 为了成功地在 Docker 中部署 Java 项目,需要准备 JDK 和打包好的 JAR 文件。确保本地已经具备这些资源。 #### 创建 `Dockerfile` 文件 创建一个名为 `Dockerfile` 的文件,在其中定义所需的环境配置以及应用启动命令: ```dockerfile FROM openjdk:8-jdk-alpine # 使用官方提供的轻量级 OpenJDK 8 镜像作为基础镜像[^1] VOLUME /tmp # 设置临时卷用于存储日志和其他数据 ARG JAR_FILE=target/*.jar # 构建参数指定 jar 包路径 COPY ${JAR_FILE} app.jar # 将编译后的 jar 复制到容器内 ENTRYPOINT ["java","-jar","/app.jar"] # 启动应用程序 ``` 此部分描述了如何基于已有的 JAR 文件来构建自定义的 Docker 映像,并指定了运行时所依赖的基础映像为包含 JDK 8 的 Alpine Linux 版本。 #### 编写 `docker-compose.yml` 文件 对于更复杂的多服务架构,可以通过编写 `docker-compose.yml` 来简化管理多个容器之间的关系: ```yaml version: '3' services: web: image: my-java-app # 替换成实际的应用名称 ports: - "8080:8080" environment: SPRING_PROFILES_ACTIVE: dev volumes: - ./logs:/var/log/app # 日志挂载点 ``` 这里展示了通过 Docker Compose 工具实现的服务组合设置方法,允许开发者轻松管理和扩展由不同组件构成的应用程序体系结构[^2]。 #### 执行构建过程 完成上述两步之后就可以执行构建操作了。进入包含这两个文件的工作目录,输入以下指令来进行映像构建: ```bash $ docker build -t java-project . ``` 这一步骤会读取当前目录下的 `Dockerfile` 并按照其指示逐步组装成一个新的 Docker 映像,最后赋予该映像标签以便后续调用[^4]。 #### 发布与测试 一旦映像被成功创建出来以后,便可以直接利用 Docker 命令将其推送到远程仓库供他人下载使用,也可以直接在本地环境中启动实例进行功能验证: ```bash $ docker run -p 8080:8080 java-project ``` 这条语句将会把主机上的端口 8080 跟容器内部暴露出来的相同编号端口建立连接,从而使得外部能够访问到正在运行当中的 Web 应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值