服务器docker应用一览

news/2025/2/22 20:40:05/

文章目录

  • 一、需求概况
  • 二、业务流程
  • 三、运行效果
  • 四、实现过程
    • 1. 基础前提
    • 2. 源码放送
    • 3.核心代码
    • 4. 项目打包
    • 5.部署步骤

一、需求概况

现有某云主机服务器,用来做项目演示用,上面运行了docker应用,现希望有一总览页面,用来展示部署的应用。

二、业务流程

获取docker信息
模板生成页面
挂载到nginx

任务调度采用crontab

三、运行效果

http://124.71.129.204

在这里插入图片描述

四、实现过程

1. 基础前提

服务器已经安装jdk、docker环境、nginx。

#安装Jdk
wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.rpmrpm -ivh jdk-8u131-linux-x64.rpmjava -version#安装nginx
vim /etc/yum.repos.d/nginx.repo[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true#查看yum的nginx信息
yum info nginx#执行命令安装
yum -y install nginx#查看安装目录
whereis nginx#设为开机启动
sudo systemctl enable nginx.service启动/停止/重启/查看状态  nginx
sudo systemctl start   nginx.service
sudo systemctl stop    nginx.service
sudo systemctl restart nginx.service
sudo systemctl status  nginx.service

2. 源码放送

https://gitcode.com/00fly/demo

git clone https://gitcode.com/00fly/demo.git

3.核心代码

在这里插入图片描述
FreeMarkerUtil

package com.fly.simple.utils;import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;/*** * FreeMarkers* * @author 00fly* @version [版本号, 2017-4-4]* @see [相关类/方法]* @since [产品/模块版本]*/
public class FreeMarkerUtil
{private static Configuration config;static{config = new Configuration(Configuration.VERSION_2_3_32);config.setDefaultEncoding(StandardCharsets.UTF_8.name());}/*** 获取模板填充model解析后的内容* * @param template* @param model* @return* @throws IOException* @throws TemplateException* @see [类、类#方法、类#成员]*/private static String renderTemplate(Template template, Map<String, Object> model)throws TemplateException, IOException{StringWriter result = new StringWriter();template.process(model, result);return result.toString();}/*** 获取模板填充model后的内容* * @param templatePath* @param model* @return* @throws IOException* @throws TemplateException* @see [类、类#方法、类#成员]*/public static String renderTemplate(String templatePath, Map<String, Object> model)throws TemplateException, IOException{config.setClassForTemplateLoading(FreeMarkerUtil.class, "/");Template template = config.getTemplate(templatePath);return renderTemplate(template, model);}
}

Executor

package com.fly.simple;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;public class Executor
{/*** execute命令* * @param command* @throws IOException* @see [类、类#方法、类#成员]*/public static List<String> execute(String command)throws IOException{List<String> resultList = new ArrayList<>();String[] cmd = SystemUtils.IS_OS_WINDOWS ? new String[] {"cmd", "/c", command} : new String[] {"/bin/sh", "-c", command};Process ps = Runtime.getRuntime().exec(cmd);try (InputStream in = ps.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in))){String line;while ((line = br.readLine()) != null){resultList.add(line);}}return resultList;}public static Map<String, Set<String>> getDockerInfo()throws IOException{String dockerCmd = "docker ps --format \"{{.Names}} {{.Ports}}\"";Map<String, Set<String>> map = new TreeMap<>();execute(dockerCmd).stream().map(line -> Collections.singletonMap(StringUtils.substringBefore(line, " "),Stream.of(StringUtils.substringAfter(line, " ").split(",")).map(p -> StringUtils.substringBetween(p, ":", "->")).filter(StringUtils::isNotBlank).map(p -> p.replace(":", "")).sorted().collect(Collectors.toSet()))).forEach(it -> map.putAll(it));return map;}
}

TemplateRun

package com.fly.simple;import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;import com.fly.simple.utils.FreeMarkerUtil;import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;@Slf4j
public class TemplateRun
{public static void main(String[] args)throws IOException, TemplateException, InterruptedException{// Jar运行,必须提供参数server.net.ipURL url = TemplateRun.class.getProtectionDomain().getCodeSource().getLocation();log.info("path: {}", url.getPath());String ip = null;if (url.getPath().endsWith(".jar")){if (args.length > 0){ip = Stream.of(args).filter(arg -> arg.contains("--server.net.ip")).map(arg -> StringUtils.substringAfter(arg, "=")).collect(Collectors.joining());log.info("server.net.ip={}", ip);}if (StringUtils.isBlank(ip)){log.error("please start jar like:\n java -jar docker-show-jar-with-dependencies.jar --server.net.ip=124.71.129.204");return;}}// 写入文件if (SystemUtils.IS_OS_WINDOWS){File file = new File("index.html");creatPage(ip, file);// 打开页面10秒后删除文件Runtime.getRuntime().exec("cmd /c start /min " + file.getCanonicalPath());TimeUnit.SECONDS.sleep(10);file.deleteOnExit();return;}if (SystemUtils.IS_OS_LINUX){// crontab -e// */30 * * * * java -jar /work/gitcode/docker-run/docker-show-jar-with-dependencies.jar --server.net.ip=124.71.129.204creatPage(ip, new File("/usr/share/nginx/html/index.html"));}}private static void creatPage(String ip, File file)throws IOException, TemplateException{// 收集docker信息Map<String, Object> model = new HashMap<>(3);model.put("date", new Date());model.put("map", Executor.getDockerInfo());model.put("ip", StringUtils.defaultIfBlank(ip, "127.0.0.1"));// {mysql5=[3306, 13306], mysql8=[23306], redis-server=[6379]}String content = FreeMarkerUtil.renderTemplate("/templates/index.html.ftl", model);try (FileWriter writer = new FileWriter(file)){writer.write(content);writer.flush();}}
}

4. 项目打包

执行mvn clean package 会在项目target 生成可执行包
在这里插入图片描述

5.部署步骤

docker-show-jar-with-dependencies.jar拷贝到服务器位置 /work/gitcode/docker-run

输入crontab -e添加如下内容,实现每30分钟执行一次生成页面,并复制到nginx首页位置/usr/share/nginx/html/index.html

*/30 * * * * java -jar /work/gitcode/docker-run/docker-show-jar-with-dependencies.jar --server.net.ip=124.71.129.204

这边的124.71.129.204为服务器ip。


有任何问题和建议,都可以向我提问讨论,大家一起进步,谢谢!

-over-


http://www.ppmy.cn/news/1422341.html

相关文章

蓝桥杯(基础题)

试题 C: 好数 时间限制 : 1.0s 内存限制: 256.0MB 本题总分&#xff1a;10 分 【问题描述】 一个整数如果按从低位到高位的顺序&#xff0c;奇数位&#xff08;个位、百位、万位 &#xff09;上 的数字是奇数&#xff0c;偶数位&#xff08;十位、千位、十万位 &…

故障转移-redis

4.4.故障转移 集群初识状态是这样的&#xff1a; 其中7001、7002、7003都是master&#xff0c;我们计划让7002宕机。 4.4.1.自动故障转移 当集群中有一个master宕机会发生什么呢&#xff1f; 直接停止一个redis实例&#xff0c;例如7002&#xff1a; redis-cli -p 7002 sh…

Unity Android Release-Notes

&#x1f308;Android Release-Notes 收集的最近几年 Unity各个版本中 Android的更新内容 本文信息收集来自自动搜集工具&#x1f448; &#x1f4a1;Android Release-Notes 2023 &#x1f4a1;Android Release-Notes 2022 &#x1f4a1;Android Release-Notes 2021

向量数据库与图数据库:理解它们的区别

作者&#xff1a;Elastic Platform Team 大数据管理不仅仅是尽可能存储更多的数据。它关乎能够识别有意义的见解、发现隐藏的模式&#xff0c;并做出明智的决策。这种对高级分析的追求一直是数据建模和存储解决方案创新的驱动力&#xff0c;远远超出了传统关系数据库。 这些创…

Kubernetes (K8s) 部署前后端分离项目

要使用Kubernetes (K8s) 部署一个涵盖Django后端、Vue前端、Redis、Nginx、RabbitMQ和MySQL的前后端分离项目,需要遵循以下步骤。这个过程涉及创建和配置多个资源,包括部署(Deployments)、服务(Services)、配置映射(ConfigMaps)、密钥(Secrets)和Ingress规则。 大纲…

【学习笔记】耳分解与无向图的双连通性

感觉之前对于这方面的理解还是不够深入。 1.1 1.1 1.1 在无向图 G ( V , E ) G(V,E) G(V,E)中&#xff0c;有一个子图 G ′ ( V ′ , E ′ ) G(V,E) G′(V′,E′)&#xff08;不一定是导出子图&#xff0c;其实只看 V ′ V V′就好了&#xff09;&#xff0c;若简单路径或简单…

零基础小白,如何入门计算机视觉?

目录 前言 计算机视觉技术学习路线 基础知识 1. 数学基础 2. 编程基础 3. 图像处理基础 基础算法与技术 1. 特征提取与描述符 2. 图像分割与对象检测 3. 三维重建与立体视觉 机器学习与深度学习 1. 机器学习基础 2. 深度学习 高级主题与应用 1. 高级机器学习与深度学习 2. 计算…

如何在MacOS上使用OpenHarmony SDK交叉编译?

本文以cJSON三方库为例介绍如何通过OpenHarmony的SDK在Mac平台进行交叉编译。 环境准备 SDK准备 我们可以通过 openHarmony SDK 官方发布渠道下载对应mac版本的SDK&#xff0c;当前OpenHarmony MAC版本的SDK有2种&#xff0c;一种是x86架构&#xff0c;另一种是arm64&#x…