Docker Remote api對docker操作-----創(chuàng)建容器

附官方api地址:https://docs.docker.com/engine/api/v1.24/

注:此方法僅僅創(chuàng)建了容器,并沒有啟動
/**
     * 創(chuàng)建容器
     * @param name 容器名稱
     * @param image 鏡像
     *@param port 端口
     * @return
     *
     */
    public static ObjectVo createDocker(String name, String image,Integer port) {
        String origin = "http://127.0.0.1:4243"; //http://+docker所在服務(wù)器的ip+docker開放的遠(yuǎn)程操作的端口
        ObjectVo vo = new ObjectVo();
        if(StringUtils.isBlank(name)||StringUtils.isBlank(image)){
            vo.setCode(0);
            vo.setMsg("參數(shù)不能為空!");
            vo.setObject(null);
            return vo;
        }

        String url = origin + "/containers/create";
        Map<String, String> param = new HashMap<>(50);
        param.put("name", name);
        try {
            ObjectVo objectVo = HttpClientUtil.doJSONRequest(url, getJSON(image,port), param);
            if (null != objectVo) {
                vo.setCode(objectVo.getCode());
                vo.setMsg(objectVo.getMsg());
                vo.setObject(objectVo.getObject());
            }else{
                vo.setCode(0);
                vo.setMsg("請求出錯,沒有返回結(jié)果");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vo;
    }
返回狀態(tài)碼,ObjectVo.code的值可以與狀態(tài)碼對比。
    201 – no error
    400 – bad parameter
    404 – no such container
    406 – impossible to attach (container not running)
    409 – conflict
    500 – server error

對docker操作的http請求

/**
     * 帶參數(shù)的HttpClient Post請求
     * @param url
     * @param json
     * @param param
     * @return
     */
    public static ObjectVo doJSONRequest(String url, String json, Map<String, String> param) {
        //創(chuàng)建HTTP客戶端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        ObjectVo objectVo = new ObjectVo();
        try {
            URIBuilder builder = new URIBuilder(url);
            //創(chuàng)建參數(shù)列表
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 創(chuàng)建Http Post請求
            HttpPost httpPost = new HttpPost(uri);
            // 創(chuàng)建請求內(nèi)容 即設(shè)置請求參數(shù)
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 執(zhí)行http請求
            response = httpClient.execute(httpPost);
            //獲取響應(yīng)狀態(tài)碼
            objectVo.setCode(response.getStatusLine().getStatusCode());
            String msg = null;
            if (null != response.getEntity()) {
                //接收響應(yīng)頭
                msg = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            if (null != msg && !msg.trim().equals("")) {
                JsonNode node =  null;
                try {
                    node = JSONUtil.getMapper().readTree(msg);
                } catch (JsonParseException e) {
                    e.printStackTrace();
                }
                objectVo.setObject(node);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //釋放連接
                response.close();
                httpClient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return objectVo;
    }
創(chuàng)建docker容器的配置文件
/**
     * 容器的一些常規(guī)配置
     * @param image 鏡像
     * @return
     */
    public static String getJSON(String image,Integer port) {
        String json =   "{\n" +
                "  \"Hostname\": \"\",\n" +
                "  \"Domainname\": \"\",\n" +
                "  \"User\": \"\",\n" +
                "  \"AttachStdin\": true,\n" +
                "  \"AttachStdout\": true,\n" +
                "  \"AttachStderr\": true,\n" +
                "  \"Tty\": false,\n" +
                "  \"OpenStdin\": true,\n" +
                "  \"StdinOnce\": false,\n" +
                "  \"Env\": [\n" +
                "    \"LANG=zh_CN.utf8\",\n" +
                "    \"BAZ=quux\"\n" +
                "  ],\n" +
                "  \"Cmd\": [\n" +
                "    \"\"\n" +
                "  ],\n" +
                "  \"Entrypoint\": \"\",\n" +
                "  \"Image\": \"IMAGE_TAG_REPLACE\",\n" +
                "  \"Labels\": {\n" +
                "    \"com.example.vendor\": \"Acme\",\n" +
                "    \"com.example.license\": \"GPL\",\n" +
                "    \"com.example.version\": \"1.0\"\n" +
                "  },\n" +
                "  \"WorkingDir\": \"\",\n" +
                "  \"NetworkDisabled\": false,\n" +
                "  \"ExposedPorts\": {\n" +
                "   \"6081/tcp\": {}\n" +
                "  },\n" +
                "  \"StopSignal\": \"SIGTERM\",\n" +
                "  \"StopTimeout\": 10,\n" +
                "  \"HostConfig\": {\n" +
                "    \"Binds\": [\n" +
                "      \"\"\n" +
                "    ],\n" +
                "    \"PortBindings\": {\n" +
                "      \"6081/tcp\": [\n" +
                "        {\n" +
                "          \"HostPort\": \"HOST_PORT_REPLACE\"\n" +
                "        }\n" +
                "       ]\n "+
                "    },\n" +
                "    \"PublishAllPorts\": false,\n" +
                "    \"Privileged\": false,\n" +
                "    \"ReadonlyRootfs\": false,\n" +
                "    \"CapAdd\": [\n" +
                "      \"NET_ADMIN\"\n" +
                "    ],\n" +
                "    \"CapDrop\": [\n" +
                "      \"MKNOD\"\n" +
                "    ],\n" +
                "    \"NetworkMode\": \"bridge\",\n" +
                "    \"Devices\": [],\n" +
                "    \"LogConfig\": {\n" +
                "      \"Type\": \"json-file\",\n" +
                "      \"Config\": {}\n" +
                "    }\n" +
                "  }\n" +
                "}";
        json = json.replace("IMAGE_TAG_REPLACE", image)
                .replace("HOST_PORT_REPLACE", port.toString());
        return json;
    }
@Data
public class ObjectVo {
    
    private Integer code;
    private String msg;
    private Object object;

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容