印尼環保英雄 扮蜘蛛人清垃圾獲民眾回響

摘錄自2020年2月17日公視報導

印尼的南蘇拉威西省,有一位超級環保英雄「蜘蛛人」,天天穿梭在各種下水道、海灘跟街道,做環境清潔工作。他的努力終於成功讓印尼民眾開始關注垃圾問題。

印尼環保人士魯迪哈托諾平時在咖啡館工作,因為希望居住環境乾淨,常常會默默穿梭在大街小巷中,清理塑膠垃圾。一開始,他的善行並沒有引發別人注意,直到他為了逗小侄子開心,買了蜘蛛人的衣服,角色扮演後,他才突發奇想,打扮成蜘蛛人清潔街道,希望引發更多人、投入清掃環境的行動。

魯迪說:「儘量減少塑膠垃圾是最重要的事情。因為塑膠很難分解。我們政府解決的方案之一,是對一次性塑膠袋進行規限。但實際上,應該要有更嚴格的規定。」

根據美國科學雜誌的研究顯示,身為全球第四人口大國,印尼每年都會產出320萬垃圾,但因為國家特殊的島嶼地形,幾乎有一半垃圾,都漂流到海裡,也讓印尼成為中國之外,世界最大的塑膠垃圾生產國。

本站聲明:網站內容來源環境資訊中心https://e-info.org.tw/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※USB CONNECTOR掌控什麼技術要點? 帶您認識其相關發展及效能

※評比前十大台北網頁設計、台北網站設計公司知名案例作品心得分享

※智慧手機時代的來臨,RWD網頁設計已成為網頁設計推薦首選

※評比南投搬家公司費用收費行情懶人包大公開

暖冬導致「熊出沒」增加 日本9個月捕殺近5700隻熊創新高

摘錄自2020年2月19日星島日報報導

據日本共同社報道,2019年4至12月日本捕殺亞洲黑熊和棕熊的數目更創歷年新高,多達5,667隻,本年度尚未結束就已創下歷史新高。

據統計,日本自2007年度起,保持捕殺1,000至3,000多隻, 2018年度為3,446頭,但19年度尚未結束,已創下新高,較18年度增加39.1%。日本專家分析,可能與熊的分布地區擴大、食物減少有關。

報道又指,去年進入12月熊的冬眠期後,仍有逾200隻熊被捕殺,專家估計可能是因為天氣暖導致熊的冬眠期推遲,因而四處覓食。2019年度至12月底為止,「熊出沒」事故的受害人達155人,其中20人受傷。

本站聲明:網站內容來源環境資訊中心https://e-info.org.tw/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※想知道網站建置、網站改版該如何進行嗎?將由專業工程師為您規劃客製化網頁設計及後台網頁設計

※不管是台北網頁設計公司、台中網頁設計公司,全省皆有專員為您服務

※Google地圖已可更新顯示潭子電動車充電站設置地點!!

※帶您來看台北網站建置,台北網頁設計,各種案例分享

SpringBoot 源碼解析 (三)—– Spring Boot 精髓:啟動時初始化數據

在我們用 springboot 搭建項目的時候,有時候會碰到在項目啟動時初始化一些操作的需求 ,針對這種需求 spring boot為我們提供了以下幾種方案供我們選擇:

  • ApplicationRunner 與 CommandLineRunner 接口

  • Spring容器初始化時InitializingBean接口和@PostConstruct

  • Spring的事件機制

ApplicationRunner與CommandLineRunner

我們可以實現 ApplicationRunner 或 CommandLineRunner 接口, 這兩個接口工作方式相同,都只提供單一的run方法,該方法在SpringApplication.run(…)完成之前調用,不知道大家還對我上一篇文章結尾有沒有印象,我們先來看看這兩個接口

public interface ApplicationRunner {
    void run(ApplicationArguments var1) throws Exception;
}

public interface CommandLineRunner {
    void run(String... var1) throws Exception;
}

都只提供單一的run方法,接下來我們來看看具體的使用

ApplicationRunner

構造一個類實現ApplicationRunner接口

//需要加入到Spring容器中
@Component public class ApplicationRunnerTest implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner");
    }
}

很簡單,首先要使用@Component將實現類加入到Spring容器中,為什麼要這樣做我們待會再看,然後實現其run方法實現自己的初始化數據邏輯就可以了

CommandLineRunner

對於這兩個接口而言,我們可以通過Order註解或者使用Ordered接口來指定調用順序, @Order() 中的值越小,優先級越高

//需要加入到Spring容器中
@Component
@Order(1)
public class CommandLineRunnerTest implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner...");
    }
}

同樣需要加入到Spring容器中,CommandLineRunner的參數是最原始的參數,沒有進行任何處理,ApplicationRunner的參數是ApplicationArguments,是對原始參數的進一步封裝

源碼分析

大家回顧一下我上一篇文章,也就是的最後一步,這裏我直接把代碼複製過來

private void callRunners(ApplicationContext context, ApplicationArguments args) {
    List<Object> runners = new ArrayList<Object>();
    //獲取容器中所有的ApplicationRunner的Bean實例
    runners.addAll(context.getBeansOfType(ApplicationRunner.class).values()); //獲取容器中所有的CommandLineRunner的Bean實例
    runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
    AnnotationAwareOrderComparator.sort(runners);
    for (Object runner : new LinkedHashSet<Object>(runners)) {
        if (runner instanceof ApplicationRunner) {
            //執行ApplicationRunner的run方法
 callRunner((ApplicationRunner) runner, args);
        }
        if (runner instanceof CommandLineRunner) {
            //執行CommandLineRunner的run方法
 callRunner((CommandLineRunner) runner, args);
        }
    }
}

很明顯,是直接從Spring容器中獲取ApplicationRunner和CommandLineRunner的實例,並調用其run方法,這也就是為什麼我要使用@Component將ApplicationRunner和CommandLineRunner接口的實現類加入到Spring容器中了。

InitializingBean

在spring初始化bean的時候,如果bean實現了 InitializingBean 接口,在對象的所有屬性被初始化后之後才會調用afterPropertiesSet()方法

@Component public class InitialingzingBeanTest implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean..");
    }
}

我們可以看出spring初始化bean肯定會在 ApplicationRunner和CommandLineRunner接口調用之前。

@PostConstruct

@Component public class PostConstructTest {

    @PostConstruct public void postConstruct() {
        System.out.println("init...");
    }
}

我們可以看到,只用在方法上添加@PostConstruct註解,並將類注入到Spring容器中就可以了。我們來看看@PostConstruct註解的方法是何時執行的

在Spring初始化bean時,對bean的實例賦值時,populateBean方法下面有一個initializeBean(beanName, exposedObject, mbd)方法,這個就是用來執行用戶設定的初始化操作。我們看下方法體:

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            // 激活 Aware 方法
            invokeAwareMethods(beanName, bean);
            return null;
        }, getAccessControlContext());
    }
    else {
        // 對特殊的 bean 處理:Aware、BeanClassLoaderAware、BeanFactoryAware
        invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        // 后處理器
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    try {
        // 激活用戶自定義的 init 方法
 invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
                (mbd != null ? mbd.getResourceDescription() : null),
                beanName, "Invocation of init method failed", ex);
    }
    if (mbd == null || !mbd.isSynthetic()) {
        // 后處理器
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }
    return wrappedBean;
}

我們看到會先執行后處理器然後執行invokeInitMethods方法,我們來看下applyBeanPostProcessorsBeforeInitialization

public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)  
        throws BeansException {  

    Object result = existingBean;  
    for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) { result = beanProcessor.postProcessBeforeInitialization(result, beanName);  
        if (result == null) {  
            return result;  
        }  
    }  
    return result;  
}

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)  
        throws BeansException {  

    Object result = existingBean;  
    for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {  
        result = beanProcessor.postProcessAfterInitialization(result, beanName);  
        if (result == null) {  
            return result;  
        }  
    }  
    return result;  
}

獲取容器中所有的後置處理器,循環調用後置處理器的postProcessBeforeInitialization方法,這裏我們來看一個BeanPostProcessor

public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {
    public CommonAnnotationBeanPostProcessor() {
        this.setOrder(2147483644);
        //設置初始化參數為PostConstruct.class
        this.setInitAnnotationType(PostConstruct.class); this.setDestroyAnnotationType(PreDestroy.class);
        this.ignoreResourceType("javax.xml.ws.WebServiceContext");
    }
    //略...
}

在構造器中設置了一個屬性為PostConstruct.class,再次觀察CommonAnnotationBeanPostProcessor這個類,它繼承自InitDestroyAnnotationBeanPostProcessor。InitDestroyAnnotationBeanPostProcessor顧名思義,就是在Bean初始化和銷毀的時候所作的一個前置/後置處理器。查看InitDestroyAnnotationBeanPostProcessor類下的postProcessBeforeInitialization方法:

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {  
  LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());  
   try {  
      metadata.invokeInitMethods(bean, beanName);  
   }  
   catch (InvocationTargetException ex) {  
       throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());  
   }  
   catch (Throwable ex) {  
       throw new BeanCreationException(beanName, "Couldn't invoke init method", ex);  
   }  
    return bean;  
}  

private LifecycleMetadata buildLifecycleMetadata(final Class clazz) {  
       final LifecycleMetadata newMetadata = new LifecycleMetadata();  
       final boolean debug = logger.isDebugEnabled();  
       ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {  
           public void doWith(Method method) {  
              if (initAnnotationType != null) {  
                   //判斷clazz中的methon是否有initAnnotationType註解,也就是PostConstruct.class註解
                  if (method.getAnnotation(initAnnotationType) != null) { //如果有就將方法添加進LifecycleMetadata中
 newMetadata.addInitMethod(method);  
                     if (debug) {  
                         logger.debug("Found init method on class [" + clazz.getName() + "]: " + method);  
                     }  
                  }  
              }  
              if (destroyAnnotationType != null) {  
                    //判斷clazz中的methon是否有destroyAnnotationType註解
                  if (method.getAnnotation(destroyAnnotationType) != null) {  
                     newMetadata.addDestroyMethod(method);  
                     if (debug) {  
                         logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method);  
                     }  
                  }  
              }  
           }  
       });  
       return newMetadata;  
} 

在這裡會去判斷某方法是否有PostConstruct.class註解,如果有,則添加到init/destroy隊列中,後續一一執行。@PostConstruct註解的方法會在此時執行,我們接着來看invokeInitMethods

protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
        throws Throwable {

    // 是否實現 InitializingBean // 如果實現了 InitializingBean 接口,則只掉調用bean的 afterPropertiesSet()
    boolean isInitializingBean = (bean instanceof InitializingBean); if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                    ((InitializingBean) bean).afterPropertiesSet();
                    return null;
                }, getAccessControlContext());
            }
            catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        }
        else {
            // 直接調用 afterPropertiesSet()
 ((InitializingBean) bean).afterPropertiesSet();
        }
    }

    if (mbd != null && bean.getClass() != NullBean.class) {
        // 判斷是否指定了 init-method(),
        // 如果指定了 init-method(),則再調用制定的init-method
        String initMethodName = mbd.getInitMethodName();
        if (StringUtils.hasLength(initMethodName) &&
                !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                !mbd.isExternallyManagedInitMethod(initMethodName)) {
            // 利用反射機制執行
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}

首先檢測當前 bean 是否實現了 InitializingBean 接口,如果實現了則調用其 afterPropertiesSet(),然後再檢查是否也指定了 init-method(),如果指定了則通過反射機制調用指定的 init-method()。

我們也可以發現@PostConstruct會在實現 InitializingBean 接口的afterPropertiesSet()方法之前執行

Spring的事件機制

基礎概念

Spring的事件驅動模型由三部分組成

  • 事件: ApplicationEvent ,繼承自JDK的 EventObject ,所有事件都要繼承它,也就是被觀察者
  • 事件發布者: ApplicationEventPublisher 及 ApplicationEventMulticaster 接口,使用這個接口,就可以發布事件了
  • 事件監聽者: ApplicationListener ,繼承JDK的 EventListener ,所有監聽者都繼承它,也就是我們所說的觀察者,當然我們也可以使用註解 @EventListener ,效果是一樣的

事件

在Spring框架中,默認對ApplicationEvent事件提供了如下支持:

  • ContextStartedEvent:ApplicationContext啟動后觸發的事件
  • ContextStoppedEvent:ApplicationContext停止后觸發的事件
  • ContextRefreshedEvent: ApplicationContext初始化或刷新完成后觸發的事件 ;(容器初始化完成后調用,所以我們可以利用這個事件做一些初始化操作)
  • ContextClosedEvent:ApplicationContext關閉后觸發的事件;(如 web 容器關閉時自動會觸發spring容器的關閉,如果是普通 java 應用,需要調用ctx.registerShutdownHook();註冊虛擬機關閉時的鈎子才行) 

構造一個類繼承ApplicationEvent

public class TestEvent extends ApplicationEvent {

    private String message;
    
    public TestEvent(Object source) {
        super(source);
    }

    public void getMessage() {
        System.out.println(message);
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

創建事件監聽者

有兩種方法可以創建監聽者,一種是直接實現ApplicationListener的接口,一種是使用註解 @EventListener , 註解是添加在監聽方法上的 ,下面的例子是直接實現的接口

@Component
public class ApplicationListenerTest implements ApplicationListener<TestEvent> {
    @Override
    public void onApplicationEvent(TestEvent testEvent) {
        testEvent.getMessage();
    }
}

事件發布

對於事件發布,代表者是 ApplicationEventPublisher 和 ApplicationEventMulticaster ,ApplicationContext接口繼承了ApplicationEventPublisher,並在AbstractApplicationContext實現了具體代碼,實際執行是委託給ApplicationEventMulticaster(可以認為是多播)

下面是一個事件發布者的測試實例:

@RunWith(SpringRunner.class)
@SpringBootTest
public class EventTest {
    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void publishTest() {
        TestEvent testEvent = new TestEvent("");
        testEvent.setMessage("hello world");
       applicationContext.publishEvent(testEvent);
    }
}

利用ContextRefreshedEvent事件進行初始化操作

利用 ContextRefreshedEvent 事件進行初始化,該事件是 ApplicationContext 初始化完成后調用的事件,所以我們可以利用這個事件,對應實現一個 監聽器 ,在其 onApplicationEvent() 方法里初始化操作

@Component public class ApplicationListenerTest implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("容器刷新完成后,我被調用了..");
    }
}

 

 

 

 

 

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理
【其他文章推薦】

※USB CONNECTOR掌控什麼技術要點? 帶您認識其相關發展及效能

※評比前十大台北網頁設計、台北網站設計公司知名案例作品心得分享

※智慧手機時代的來臨,RWD網頁設計已成為網頁設計推薦首選

※台灣海運大陸貨務運送流程

※兩岸物流進出口一站式服務

奇瑞新建輕量電動車生產線 年產能可達6萬輛

據報導,奇瑞新工廠將投產鋁車身骨架純電動乘用車,年產能可達6萬輛,主要生產S51EV、小螞蟻、AOEV等系列電動車。此外新工廠投產後,將成為奇瑞兌現年產20萬輛新能源車產能目標的重要一環。

奇瑞新電動車生產項目位於蕪湖弋江區高新技術開發區,項目總投資15.6億元人民幣,由奇瑞汽車股份有限公司獨資建設,有望於年內正式投產。

奇瑞汽車股份有限公司總經理助理劉志佳此前表示,奇瑞後續的新能源汽車產品,都是以鋁合金框架(含電池鋁合金框架)和分體式碳纖維於一體的輕量化產品構架平臺。今年10月,奇瑞將推出該輕量化平臺打造的首款車型,車身減重將達到30%,該車型的推出會為減排起到很大作用,同時新車的製造過程對於傳統四大工藝(衝壓、焊裝、塗裝、總裝)也將是很大的挑戰。

據劉志佳介紹,2016年奇瑞將新能源車銷量目標定為3.3萬輛,其中純電車目標為28,000輛,插電式混合動力車目標是5,000輛。與2015年銷量表現相比,其今年銷量將實現133%的增幅。

按照奇瑞此前公佈的消息,奇瑞目前已形成全系列的新能源乘用車研發體系和集成平臺,包括四大新能源整車平臺(小型純電動平臺、中型純電動平臺、插電式混動平臺、電四驅平臺);五大通用子系統(動力電池系統、電驅動系統、整車控制系統、PHEV動力總成、電驅動後橋);七大核心技術(電池管理技術、電池系統設計、整車控制技術、PHEV系統設計、智慧互聯設計、輕量化技術、新能源整車集成)。

本站聲明:網站內容來源於EnergyTrend https://www.energytrend.com.tw/ev/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※USB CONNECTOR掌控什麼技術要點? 帶您認識其相關發展及效能

※評比前十大台北網頁設計、台北網站設計公司知名案例作品心得分享

※智慧手機時代的來臨,RWD網頁設計已成為網頁設計推薦首選

※台灣海運大陸貨務運送流程

※兩岸物流進出口一站式服務

馬斯克承認低油價不利電動車銷售,但稱特斯拉較不受影響

油價直直落,美國人大買耗油車,這股風潮豈不是對電動車相當不利?特斯拉(Tesla)執行長艾隆‧馬斯克(Elon Musk)於 2016 年 1 月底受邀前往香港 StartmeupHK 新創論壇(StartmeupHK Venture Forum)擔任演講來賓,在香港受 CNN 訪問時,承認低油價對整體電動車市場不利,但認為特斯拉將比其他電動車對手更不受影響。

馬斯克承認低油價對電動車的不利影響,表示這符合經濟常識。事實上,低油價已經使得 2015 年美國車市燒油較兇的貨卡以及休旅車大行其道,就更大的市場方向來說,油價的經濟考量,也顯然會對消費者在傳統燃油車、油電混合車,以及全電動車之間的選擇發生影響力。   不過馬斯克認為,特斯拉受到的影響將較其他電動車對手小,因為特斯拉將本身定位於高檔市場,因此其消費者購車時的經濟考量程度較輕,相對的,馬斯克認為以低價搶市的電動車對手,面對低油價讓燃油車更為經濟的情況,將會大受打擊,他表示,有些電動車和燃油車車款除了動力來源並沒有基本差異,如此一來,消費者只會比較經濟面,這樣的電動車對手將會在低油價下受到重大影響,但是馬斯克認為就算低油價讓燃油車更為經濟,特斯拉的 Model 3 仍然會表現良好。Model 3 是特斯拉較為大眾取向的車款,車價 3.4 萬美元,相當於約 114 萬元新台幣。   馬斯克也歡迎其他車廠共襄盛舉,一同推出更多電動車,可把餅做大,如通用汽車(GM)的雪佛蘭(Chevrolet)Bolt,馬斯克表示,若通用汽車或其他車廠開發出讓消費者滿意的電動車,對世界是好事,他會歡迎它們。   馬斯克也談及中國市場,表示中國電動車市場雖然只是剛開始起步,但正朝向正確的方向邁進,他表示有些中國公司,指巴菲特投資的比亞迪,正朝著製造出性能良好電動車的方向前進,進展快速。不過,特斯拉本身在中國市場表現並不理想,要如何在中國建立生產線,特斯拉還在嘗試中,而身為進口車,特斯拉要蒙受高額進口稅,且無法得到中國政府對電動車的補貼,因此受到相當大的阻礙,一旦能在中國本地生產,將對生意有相當大助益。   馬斯克認為中國政府政策將不可避免的往電動車傾斜,以減輕空氣污染與碳排放,中國政府也了解電動車對未來相當重要,想讓城市擁有潔淨空氣,就必須發展電動車。馬斯克認為 Model 3 終有一天會在中國生產,不過可能要 3 年才能辦得到這點。

(首圖來源:)    (本文授權轉載自《》─〈〉)

本站聲明:網站內容來源於EnergyTrend https://www.energytrend.com.tw/ev/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※想知道網站建置、網站改版該如何進行嗎?將由專業工程師為您規劃客製化網頁設計及後台網頁設計

※不管是台北網頁設計公司、台中網頁設計公司,全省皆有專員為您服務

※Google地圖已可更新顯示潭子電動車充電站設置地點!!

※帶您來看台北網站建置,台北網頁設計,各種案例分享

※小三通物流營運型態?

※快速運回,大陸空運推薦?

Docker學習(五)-Kubernetes 集群搭建 – Spring Boot 應用,Docker學習-Docker搭建Consul集群,Docker學習-簡單的私有DockerHub搭建,Docker學習-Spring Boot on Docker,Docker學習-Kubernetes – 集群部署,Docker學習-Kubernetes – Spring Boot 應用,Docker學習-Kubernetes – Spring Boot 應用

 

Docker學習

 

 

簡介

kubernetes,簡稱K8s,是用8代替8個字符“ubernete”而成的縮寫。是一個開源的,用於管理雲平台中多個主機上的容器化的應用,Kubernetes的目標是讓部署容器化的應用簡單並且高效(powerful),Kubernetes提供了應用部署,規劃,更新,維護的一種機制。

Kubernetes是Google開源的一個容器編排引擎,它支持自動化部署、大規模可伸縮、應用容器化管理。在生產環境中部署一個應用程序時,通常要部署該應用的多個實例以便對應用請求進行負載均衡。 在Kubernetes中,我們可以創建多個容器,每個容器裏面運行一個應用實例,然後通過內置的負載均衡策略,實現對這一組應用實例的管理、發現、訪問,而這些細節都不需要運維人員去進行複雜的手工配置和處理。  

基本概念

Kubernetes 中的絕大部分概念都抽象成 Kubernetes 管理的一種資源對象

  • Master:Master 節點是 Kubernetes 集群的控制節點,負責整個集群的管理和控制。Master 節點上包含以下組件:
  • kube-apiserver:集群控制的入口,提供 HTTP REST 服務
  • kube-controller-manager:Kubernetes 集群中所有資源對象的自動化控制中心
  • kube-scheduler:負責 Pod 的調度
  • Node:Node 節點是 Kubernetes 集群中的工作節點,Node 上的工作負載由 Master 節點分配,工作負載主要是運行容器應用。Node 節點上包含以下組件:

    • kubelet:負責 Pod 的創建、啟動、監控、重啟、銷毀等工作,同時與 Master 節點協作,實現集群管理的基本功能。
    • kube-proxy:實現 Kubernetes Service 的通信和負載均衡
    • 運行容器化(Pod)應用
  • Pod: Pod 是 Kubernetes 最基本的部署調度單元。每個 Pod 可以由一個或多個業務容器和一個根容器(Pause 容器)組成。一個 Pod 表示某個應用的一個實例

  • ReplicaSet:是 Pod 副本的抽象,用於解決 Pod 的擴容和伸縮
  • Deployment:Deployment 表示部署,在內部使用ReplicaSet 來實現。可以通過 Deployment 來生成相應的 ReplicaSet 完成 Pod 副本的創建
  • Service:Service 是 Kubernetes 最重要的資源對象。Kubernetes 中的 Service 對象可以對應微服務架構中的微服務。Service 定義了服務的訪問入口,服務的調用者通過這個地址訪問 Service 後端的 Pod 副本實例。Service 通過 Label Selector 同後端的 Pod 副本建立關係,Deployment 保證後端Pod 副本的數量,也就是保證服務的伸縮性。

Kubernetes 主要由以下幾個核心組件組成:

  • etcd 保存了整個集群的狀態,就是一個數據庫;
  • apiserver 提供了資源操作的唯一入口,並提供認證、授權、訪問控制、API 註冊和發現等機制;
  • controller manager 負責維護集群的狀態,比如故障檢測、自動擴展、滾動更新等;
  • scheduler 負責資源的調度,按照預定的調度策略將 Pod 調度到相應的機器上;
  • kubelet 負責維護容器的生命周期,同時也負責 Volume(CSI)和網絡(CNI)的管理;
  • Container runtime 負責鏡像管理以及 Pod 和容器的真正運行(CRI);
  • kube-proxy 負責為 Service 提供 cluster 內部的服務發現和負載均衡;

當然了除了上面的這些核心組件,還有一些推薦的插件:

  • kube-dns 負責為整個集群提供 DNS 服務
  • Ingress Controller 為服務提供外網入口
  • Heapster 提供資源監控
  • Dashboard 提供 GUI

組件通信

Kubernetes 多組件之間的通信原理:

  • apiserver 負責 etcd 存儲的所有操作,且只有 apiserver 才直接操作 etcd 集群
  • apiserver 對內(集群中的其他組件)和對外(用戶)提供統一的 REST API,其他組件均通過 apiserver 進行通信

    • controller manager、scheduler、kube-proxy 和 kubelet 等均通過 apiserver watch API 監測資源變化情況,並對資源作相應的操作
    • 所有需要更新資源狀態的操作均通過 apiserver 的 REST API 進行
  • apiserver 也會直接調用 kubelet API(如 logs, exec, attach 等),默認不校驗 kubelet 證書,但可以通過 --kubelet-certificate-authority 開啟(而 GKE 通過 SSH 隧道保護它們之間的通信)

比如最典型的創建 Pod 的流程:​​

  • 用戶通過 REST API 創建一個 Pod
  • apiserver 將其寫入 etcd
  • scheduluer 檢測到未綁定 Node 的 Pod,開始調度並更新 Pod 的 Node 綁定
  • kubelet 檢測到有新的 Pod 調度過來,通過 container runtime 運行該 Pod
  • kubelet 通過 container runtime 取到 Pod 狀態,並更新到 apiserver 中

 

集群部署

 

使用kubeadm工具安裝

1. master和node 都用yum 安裝kubelet,kubeadm,docker
2. master 上初始化:kubeadm init
3. master 上啟動一個flannel的pod
4. node上加入集群:kubeadm join

 

準備環境

Centos7  192.168.50.21 k8s-master  
Centos7  192.168.50.22 k8s-node01
Centos7  192.168.50.23 k8s-node02

修改主機名(3台機器都需要修改)

hostnamectl set-hostname k8s-master
hostnamectl set-hostname k8s-node01
hostnamectl set-hostname k8s-node02

關閉防火牆

systemctl stop firewalld.service

配置docker yum源

yum install -y yum-utils device-mapper-persistent-data lvm2 wget
cd /etc/yum.repos.d
wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

配置kubernetes yum 源

cd /opt/
wget https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg
wget https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
rpm --import yum-key.gpg
rpm --import rpm-package-key.gpg
cd /etc/yum.repos.d
vi kubernetes.repo 
輸入以下內容
[kubernetes]
name=Kubernetes Repo
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg
enabled=1

yum repolist

master和node 安裝kubelet,kubeadm,docker

yum install docker 
yum install kubelet-1.13.1
yum install kubeadm-1.13.1

master 上安裝kubectl

yum install kubectl-1.13.1

docker的配置

配置私有倉庫和鏡像加速地址,私有倉庫配置參見 

vi /etc/docker/daemon.json

 

{
    "registry-mirror":[
        "http://hub-mirror.c.163.com"
    ],
    "insecure-registries":[
        "192.168.50.24:5000"
    ]
}

 

啟動docker

systemctl daemon-reload
systemctl start docker 
docker info

master 上初始化:kubeadm init 

vi /etc/sysconfig/kubelet
KUBELET_EXTRA_ARGS="--fail-swap-on=false"
kubeadm init \
    --apiserver-advertise-address=192.168.50.21 \
    --image-repository registry.aliyuncs.com/google_containers \
    --kubernetes-version v1.13.1 \
    --pod-network-cidr=10.244.0.0/16

初始化命令說明:

--apiserver-advertise-address

指明用 Master 的哪個 interface 與 Cluster 的其他節點通信。如果 Master 有多個 interface,建議明確指定,如果不指定,kubeadm 會自動選擇有默認網關的 interface。

--pod-network-cidr

指定 Pod 網絡的範圍。Kubernetes 支持多種網絡方案,而且不同網絡方案對 –pod-network-cidr 有自己的要求,這裏設置為 10.244.0.0/16 是因為我們將使用 flannel 網絡方案,必須設置成這個 CIDR。

--image-repository

Kubenetes默認Registries地址是 k8s.gcr.io,在國內並不能訪問 gcr.io,在1.13版本中我們可以增加–image-repository參數,默認值是 k8s.gcr.io,將其指定為阿里雲鏡像地址:registry.aliyuncs.com/google_containers。

--kubernetes-version=v1.13.1 

關閉版本探測,因為它的默認值是stable-1,會導致從https://dl.k8s.io/release/stable-1.txt下載最新的版本號,我們可以將其指定為固定版本(最新版:v1.13.1)來跳過網絡請求。

初始化過程中

[preflight] You can also perform this action in beforehand using 'kubeadm config images pull' 是在下載鏡像文件,過程比較慢。
[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s
[apiclient] All control plane components are healthy after 24.002300 seconds 這個過程也比較慢 可以忽略
 
[init] Using Kubernetes version: v1.13.1
[preflight] Running pre-flight checks
[preflight] Pulling images required for setting up a Kubernetes cluster
[preflight] This might take a minute or two, depending on the speed of your internet connection
[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Activating the kubelet service
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Generating "ca" certificate and key
[certs] Generating "apiserver-kubelet-client" certificate and key
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [k8s-master kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 192.168.50.21]
[certs] Generating "front-proxy-ca" certificate and key
[certs] Generating "front-proxy-client" certificate and key
[certs] Generating "etcd/ca" certificate and key
[certs] Generating "etcd/healthcheck-client" certificate and key
[certs] Generating "apiserver-etcd-client" certificate and key
[certs] Generating "etcd/server" certificate and key
[certs] etcd/server serving cert is signed for DNS names [k8s-master localhost] and IPs [192.168.50.21 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [k8s-master localhost] and IPs [192.168.50.21 127.0.0.1 ::1]
[certs] Generating "sa" key and public key
[kubeconfig] Using kubeconfig folder "/etc/kubernetes"
[kubeconfig] Writing "admin.conf" kubeconfig file
[kubeconfig] Writing "kubelet.conf" kubeconfig file
[kubeconfig] Writing "controller-manager.conf" kubeconfig file
[kubeconfig] Writing "scheduler.conf" kubeconfig file
[control-plane] Using manifest folder "/etc/kubernetes/manifests"
[control-plane] Creating static Pod manifest for "kube-apiserver"
[control-plane] Creating static Pod manifest for "kube-controller-manager"
[control-plane] Creating static Pod manifest for "kube-scheduler"
[etcd] Creating static Pod manifest for local etcd in "/etc/kubernetes/manifests"
[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s
[apiclient] All control plane components are healthy after 24.002300 seconds
[uploadconfig] storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.13" in namespace kube-system with the configuration for the kubelets in the cluster
[patchnode] Uploading the CRI Socket information "/var/run/dockershim.sock" to the Node API object "k8s-master" as an annotation
[mark-control-plane] Marking the node k8s-master as control-plane by adding the label "node-role.kubernetes.io/master=''"
[mark-control-plane] Marking the node k8s-master as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[bootstrap-token] Using token: 7ax0k4.nxpjjifrqnbrpojv
[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles
[bootstraptoken] configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials
[bootstraptoken] configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token
[bootstraptoken] configured RBAC rules to allow certificate rotation for all node client certificates in the cluster
[bootstraptoken] creating the "cluster-info" ConfigMap in the "kube-public" namespace
[addons] Applied essential addon: CoreDNS
[addons] Applied essential addon: kube-proxy

Your Kubernetes master has initialized successfully!

To start using your cluster, you need to run the following as a regular user:

  mkdir -p $HOME/.kube
  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
  sudo chown $(id -u):$(id -g) $HOME/.kube/config

You should now deploy a pod network to the cluster.
Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:
  https://kubernetes.io/docs/concepts/cluster-administration/addons/

You can now join any number of machines by running the following on each node
as root:

  kubeadm join 192.168.50.21:6443 --token 7ax0k4.nxpjjifrqnbrpojv --discovery-token-ca-cert-hash sha256:95942f10859a71879c316e75498de02a8b627725c37dee33f74cd040e1cd9d6b

初始化過程說明:

1) [preflight] kubeadm 執行初始化前的檢查。
2) [kubelet-start] 生成kubelet的配置文件”/var/lib/kubelet/config.yaml”
3) [certificates] 生成相關的各種token和證書
4) [kubeconfig] 生成 KubeConfig 文件,kubelet 需要這個文件與 Master 通信
5) [control-plane] 安裝 Master 組件,會從指定的 Registry 下載組件的 Docker 鏡像。
6) [bootstraptoken] 生成token記錄下來,後邊使用kubeadm join往集群中添加節點時會用到
7) [addons] 安裝附加組件 kube-proxy 和 kube-dns。
8) Kubernetes Master 初始化成功,提示如何配置常規用戶使用kubectl訪問集群。
9) 提示如何安裝 Pod 網絡。
10) 提示如何註冊其他節點到 Cluster。

 

異常情況:

 [WARNING Service-Docker]: docker service is not enabled, please run 'systemctl enable docker.service'
        [WARNING Swap]: running with swap on is not supported. Please disable swap
        [WARNING Hostname]: hostname "k8s-master" could not be reached
        [WARNING Hostname]: hostname "k8s-master": lookup k8s-master on 114.114.114.114:53: no such host
        [WARNING Service-Kubelet]: kubelet service is not enabled, please run 'systemctl enable kubelet.service'

運行

systemctl enable docker.service
systemctl enable kubelet.service

會提示以下錯誤

  [WARNING Hostname]: hostname "k8s-master" could not be reached
        [WARNING Hostname]: hostname "k8s-master": lookup k8s-master on 114.114.114.114:53: no such host
error execution phase preflight: [preflight] Some fatal errors occurred:

配置host

cat >> /etc/hosts << EOF
192.168.50.21 k8s-master
192.168.50.22 k8s-node01
192.168.50.23 k8s-node02
EOF

再次運行初始化命令會出現

  [ERROR NumCPU]: the number of available CPUs 1 is less than the required 2   --設置虛擬機CPU個數大於2
        [ERROR FileContent--proc-sys-net-bridge-bridge-nf-call-iptables]: /proc/sys/net/bridge/bridge-nf-call-iptables contents are not set to 1
echo 1 > /proc/sys/net/bridge/bridge-nf-call-iptables echo 1 > /proc/sys/net/bridge/bridge-nf-call-ip6tables

設置好虛擬機CPU個數,重啟后再次運行:

kubeadm init \
    --apiserver-advertise-address=192.168.50.21 \
    --image-repository registry.aliyuncs.com/google_containers \
    --kubernetes-version v1.13.1 \
    --pod-network-cidr=10.244.0.0/16

 

[init] Using Kubernetes version: v1.13.1
[preflight] Running pre-flight checks
[preflight] Pulling images required for setting up a Kubernetes cluster
[preflight] This might take a minute or two, depending on the speed of your internet connection
[preflight] You can also perform this action in beforehand using 'kubeadm config images pull

解決辦法:docker.io倉庫對google的容器做了鏡像,可以通過下列命令下拉取相關鏡像

先看下需要用到哪些

kubeadm config images list

配置yum源

[root@k8s-master opt]# vi kubeadm-config.yaml
apiVersion: kubeadm.k8s.io/v1beta1
kind: ClusterConfiguration
kubernetesVersion: v1.13.1
imageRepository: registry.aliyuncs.com/google_containers
apiServer:
  certSANs:
  - 192.168.50.21
controlPlaneEndpoint: "192.168.50.20:16443"
networking:
  # This CIDR is a Calico default. Substitute or remove for your CNI provider.
  podSubnet: "172.168.0.0/16"
 kubeadm config images pull --config /opt/kubeadm-config.yaml

初始化master

kubeadm init --config=kubeadm-config.yaml  --upload-certs

 

xecution phase preflight: [preflight] Some fatal errors occurred:
        [ERROR FileAvailable--etc-kubernetes-manifests-kube-apiserver.yaml]: /etc/kubernetes/manifests/kube-apiserver.yaml already exists
        [ERROR FileAvailable--etc-kubernetes-manifests-kube-controller-manager.yaml]: /etc/kubernetes/manifests/kube-controller-manager.yaml already exists
        [ERROR FileAvailable--etc-kubernetes-manifests-kube-scheduler.yaml]: /etc/kubernetes/manifests/kube-scheduler.yaml already exists
        [ERROR FileAvailable--etc-kubernetes-manifests-etcd.yaml]: /etc/kubernetes/manifests/etcd.yaml already exists
        [ERROR Port-10250]: Port 10250 is in use

kubeadm會自動檢查當前環境是否有上次命令執行的“殘留”。如果有,必須清理后再行執行init。我們可以通過”kubeadm reset”來清理環境,以備重來。

[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s
[kubelet-check] Initial timeout of 40s passed.

==原因==

這是因為kubelet沒啟動

==解決==

systemctl restart kubelet

如果啟動不了kubelet

kubelet.service - kubelet: The Kubernetes Node Agent

 

則可能是swap交換分區還開啟的原因
-關閉swap

swapoff -a

-配置kubelet

vi /etc/sysconfig/kubelet
KUBELET_EXTRA_ARGS="--fail-swap-on=false"

 再次運行

kubeadm init \
    --apiserver-advertise-address=192.168.50.21 \
    --image-repository registry.aliyuncs.com/google_containers \
    --kubernetes-version v1.13.1 \
    --pod-network-cidr=10.244.0.0/16

 

 

配置 kubectl

kubectl 是管理 Kubernetes Cluster 的命令行工具,前面我們已經在所有的節點安裝了 kubectl。Master 初始化完成后需要做一些配置工作,然後 kubectl 就能使用了。
依照 kubeadm init 輸出的最後提示,推薦用 Linux 普通用戶執行 kubectl。

  • 創建普通用戶centos
#創建普通用戶並設置密碼123456
useradd centos && echo "centos:123456" | chpasswd centos

#追加sudo權限,並配置sudo免密
sed -i '/^root/a\centos  ALL=(ALL)       NOPASSWD:ALL' /etc/sudoers

#保存集群安全配置文件到當前用戶.kube目錄
su - centos
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

#啟用 kubectl 命令自動補全功能(註銷重新登錄生效)
echo "source <(kubectl completion bash)" >> ~/.bashrc

需要這些配置命令的原因是:Kubernetes 集群默認需要加密方式訪問。所以,這幾條命令,就是將剛剛部署生成的 Kubernetes 集群的安全配置文件,保存到當前用戶的.kube 目錄下,kubectl 默認會使用這個目錄下的授權信息訪問 Kubernetes 集群。
如果不這麼做的話,我們每次都需要通過 export KUBECONFIG 環境變量告訴 kubectl 這個安全配置文件的位置。
配置完成后centos用戶就可以使用 kubectl 命令管理集群了。

查看集群狀態:

kubectl get cs

 

 

 

 

 

 部署網絡插件

kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

  

kubectl get 重新檢查 Pod 的狀態

 

 

部署worker節點

 在master機器保存生成號的鏡像文件

docker save -o master.tar registry.aliyuncs.com/google_containers/kube-proxy:v1.13.1 registry.aliyuncs.com/google_containers/kube-apiserver:v1.13.1 registry.aliyuncs.com/google_containers/kube-controller-manager:v1.13.1 registry.aliyuncs.com/google_containers/kube-scheduler:v1.13.1  registry.aliyuncs.com/google_containers/coredns:1.2.6  registry.aliyuncs.com/google_containers/etcd:3.2.24 registry.aliyuncs.com/google_containers/pause:3.1

注意對應的版本號

將master上保存的鏡像同步到節點上

scp master.tar node01:/root/
scp master.tar node02:/root/

將鏡像導入本地,node01,node02

 docker load< master.tar

配置host,node01,node02

cat >> /etc/hosts << EOF
192.168.50.21 k8s-master
192.168.50.22 k8s-node01
192.168.50.23 k8s-node02
EOF

配置iptables,node01,node02

echo 1 > /proc/sys/net/bridge/bridge-nf-call-iptables
echo 1 > /proc/sys/net/bridge/bridge-nf-call-ip6tables

-關閉swap,node01,node02

swapoff -a

-配置kubelet,node01,node02

vi /etc/sysconfig/kubelet
KUBELET_EXTRA_ARGS="--fail-swap-on=false" 
systemctl enable docker.service
systemctl enable kubelet.service

啟動docker,node01,node02

service docker strat

部署網絡插件,node01,node02

kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

獲取join指令,master

kubeadm token create --print-join-command
kubeadm token create --print-join-command
kubeadm join 192.168.50.21:6443 --token n9g4nq.kf8ppgpgb3biz0n5 --discovery-token-ca-cert-hash sha256:95942f10859a71879c316e75498de02a8b627725c37dee33f74cd040e1cd9d6b

 

在子節點運行指令 ,node01,node02

kubeadm join 192.168.50.21:6443 --token n9g4nq.kf8ppgpgb3biz0n5 --discovery-token-ca-cert-hash sha256:95942f10859a71879c316e75498de02a8b627725c37dee33f74cd040e1cd9d6b
[preflight] Running pre-flight checks
[discovery] Trying to connect to API Server "192.168.50.21:6443"
[discovery] Created cluster-info discovery client, requesting info from "https://192.168.50.21:6443"
[discovery] Requesting info from "https://192.168.50.21:6443" again to validate TLS against the pinned public key
[discovery] Cluster info signature and contents are valid and TLS certificate validates against pinned roots, will use API Server "192.168.50.21:6443"
[discovery] Successfully established connection with API Server "192.168.50.21:6443"
[join] Reading configuration from the cluster...
[join] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -oyaml'
[kubelet-start] WARNING: unable to stop the kubelet service momentarily: [exit status 4]
[kubelet] Downloading configuration for the kubelet from the "kubelet-config-1.13" ConfigMap in the kube-system namespace
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Activating the kubelet service
[tlsbootstrap] Waiting for the kubelet to perform the TLS Bootstrap...
[patchnode] Uploading the CRI Socket information "/var/run/dockershim.sock" to the Node API object "k8s-node01" as an annotation

This node has joined the cluster:
* Certificate signing request was sent to apiserver and a response was received.
* The Kubelet was informed of the new secure connection details.

Run 'kubectl get nodes' on the master to see this node join the cluster.

在master上查看節點狀態

kubectl get nodes

 

 這種狀態是錯誤的 ,只有一台聯機正確

查看node01,和node02發現 node01有些進程沒有完全啟動

刪除node01所有運行的容器,node01

docker stop $(docker ps -q) & docker rm $(docker ps -aq)

重置 kubeadm ,node01

kubeadm reset

獲取join指令,master

kubeadm token create --print-join-command

再次在node01上運行join

 

 

 

查看node01鏡像運行狀態

  

查看master狀態

  

nodes狀態全部為ready,由於每個節點都需要啟動若干組件,如果node節點的狀態是 NotReady,可以查看所有節點pod狀態,確保所有pod成功拉取到鏡像並處於running狀態:

kubectl get pod --all-namespaces -o wide

  

配置kubernetes UI圖形化界面

創建kubernetes-dashboard.yaml

# Copyright 2017 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# ------------------- Dashboard Secret ------------------- #

apiVersion: v1
kind: Secret
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard-certs
  namespace: kube-system
type: Opaque

---
# ------------------- Dashboard Service Account ------------------- #

apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard
  namespace: kube-system

---
# ------------------- Dashboard Role & Role Binding ------------------- #

kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: kubernetes-dashboard-minimal
  namespace: kube-system
rules:
  # Allow Dashboard to create 'kubernetes-dashboard-key-holder' secret.
- apiGroups: [""]
  resources: ["secrets"]
  verbs: ["create"]
  # Allow Dashboard to create 'kubernetes-dashboard-settings' config map.
- apiGroups: [""]
  resources: ["configmaps"]
  verbs: ["create"]
  # Allow Dashboard to get, update and delete Dashboard exclusive secrets.
- apiGroups: [""]
  resources: ["secrets"]
  resourceNames: ["kubernetes-dashboard-key-holder", "kubernetes-dashboard-certs"]
  verbs: ["get", "update", "delete"]
  # Allow Dashboard to get and update 'kubernetes-dashboard-settings' config map.
- apiGroups: [""]
  resources: ["configmaps"]
  resourceNames: ["kubernetes-dashboard-settings"]
  verbs: ["get", "update"]
  # Allow Dashboard to get metrics from heapster.
- apiGroups: [""]
  resources: ["services"]
  resourceNames: ["heapster"]
  verbs: ["proxy"]
- apiGroups: [""]
  resources: ["services/proxy"]
  resourceNames: ["heapster", "http:heapster:", "https:heapster:"]
  verbs: ["get"]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: kubernetes-dashboard-minimal
  namespace: kube-system
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: kubernetes-dashboard-minimal
subjects:
- kind: ServiceAccount
  name: kubernetes-dashboard
  namespace: kube-system

---
# ------------------- Dashboard Deployment ------------------- #

kind: Deployment
apiVersion: apps/v1
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard
  namespace: kube-system
spec:
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      k8s-app: kubernetes-dashboard
  template:
    metadata:
      labels:
        k8s-app: kubernetes-dashboard
    spec:
      containers:
      - name: kubernetes-dashboard
        image: registry.cn-hangzhou.aliyuncs.com/rsqlh/kubernetes-dashboard:v1.10.1  
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 8443
          protocol: TCP
        args:
          - --auto-generate-certificates
          # Uncomment the following line to manually specify Kubernetes API server Host
          # If not specified, Dashboard will attempt to auto discover the API server and connect
          # to it. Uncomment only if the default does not work.
          # - --apiserver-host=http://my-address:port
        volumeMounts:
        - name: kubernetes-dashboard-certs
          mountPath: /certs
          # Create on-disk volume to store exec logs
        - mountPath: /tmp
          name: tmp-volume
        livenessProbe:
          httpGet:
            scheme: HTTPS
            path: /
            port: 8443
          initialDelaySeconds: 30
          timeoutSeconds: 30
      volumes:
      - name: kubernetes-dashboard-certs
        secret:
          secretName: kubernetes-dashboard-certs
      - name: tmp-volume
        emptyDir: {}
      serviceAccountName: kubernetes-dashboard
      # Comment the following tolerations if Dashboard must not be deployed on master
      tolerations:
      - key: node-role.kubernetes.io/master
        effect: NoSchedule

---
# ------------------- Dashboard Service ------------------- #

kind: Service
apiVersion: v1
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard
  namespace: kube-system
spec:
  type: NodePort
  ports:
  - port: 443
    targetPort: 8443
    nodePort: 30000
  selector:
    k8s-app: kubernetes-dashboard

 

執行以下命令創建kubernetes-dashboard:

kubectl create -f kubernetes-dashboard.yaml

如果出現

Error from server (AlreadyExists): error when creating "kubernetes-dashboard.yaml": secrets "kubernetes-dashboard-certs" already exists
Error from server (AlreadyExists): error when creating "kubernetes-dashboard.yaml": serviceaccounts "kubernetes-dashboard" already exists
Error from server (AlreadyExists): error when creating "kubernetes-dashboard.yaml": roles.rbac.authorization.k8s.io "kubernetes-dashboard-minimal" already exists
Error from server (AlreadyExists): error when creating "kubernetes-dashboard.yaml": rolebindings.rbac.authorization.k8s.io "kubernetes-dashboard-minimal" already exists
Error from server (AlreadyExists): error when creating "kubernetes-dashboard.yaml": deployments.apps "kubernetes-dashboard" already exists

運行delete清理

kubectl delete -f kubernetes-dashboard.yaml

查看組件運行狀態

kubectl get pods --all-namespaces

 

 

 ErrImagePull 拉取鏡像失敗

手動拉取 並重置tag

docker pull registry.cn-hangzhou.aliyuncs.com/rsqlh/kubernetes-dashboard:v1.10.1
docker tag registry.cn-hangzhou.aliyuncs.com/rsqlh/kubernetes-dashboard:v1.10.1 k8s.gcr.io/kubernetes-dashboard-amd64:v1.10.1

重新創建

  

 

ImagePullBackOff

默認情況是會根據配置文件中的鏡像地址去拉取鏡像,如果設置為IfNotPresent 和Never就會使用本地鏡像。

IfNotPresent :如果本地存在鏡像就優先使用本地鏡像。
Never:直接不再去拉取鏡像了,使用本地的;如果本地不存在就報異常了。

 spec:
      containers:
      - name: kubernetes-dashboard
        image: registry.cn-hangzhou.aliyuncs.com/rsqlh/kubernetes-dashboard:v1.10.1  
        imagePullPolicy: IfNotPresent

 

查看映射狀態 

 kubectl get service  -n kube-system

 

 

 

 

創建能夠訪問 Dashboard 的用戶

 新建文件 account.yaml ,內容如下:

# Create Service Account
apiVersion: v1
kind: ServiceAccount
metadata:
  name: admin-user
  namespace: kube-system
---
# Create ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: admin-user
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: admin-user
  namespace: kube-system
kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}')

 

 複製token登陸

 

 

configmaps is forbidden: User "system:serviceaccount:kube-system:admin-user" cannot list resource "configmaps" in API group "" in the namespace "default" 

 授權用戶

kubectl create clusterrolebinding test:admin-user --clusterrole=cluster-admin --serviceaccount=kube-system:admin-user

 

 

 NodePort方式,可以到任意一個節點的XXXX端口查看

 

 

本文參考:

 

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理
【其他文章推薦】

※USB CONNECTOR掌控什麼技術要點? 帶您認識其相關發展及效能

※評比前十大台北網頁設計、台北網站設計公司知名案例作品心得分享

※智慧手機時代的來臨,RWD網頁設計已成為網頁設計推薦首選

※台灣海運大陸貨務運送流程

※兩岸物流進出口一站式服務

使用JaCoCo Maven插件創建代碼覆蓋率報告

這篇博客文章描述了我們如何使用JaCoCo Maven插件為單元和集成測試創建代碼覆蓋率報告。

我們的構建要求如下:

運行測試時,我們的構建必須為單元測試和集成測試創建代碼覆蓋率報告。
代碼覆蓋率報告必須在單獨的目錄中創建。換句話說,必須將用於單元測試的代碼覆蓋率報告創建到與用於集成測試的代碼覆蓋率報告不同的目錄中。
讓我們開始吧。

配置JaCoCo Maven插件

我們使用JaCoCo Maven插件有兩個目的:

  • 它使我們可以訪問JaCoCo運行時代理,該代理記錄了執行覆蓋率數據。
  • 它根據JaCo​​Co運行時代理記錄的執行數據創建代碼覆蓋率報告。
  • 我們可以按照以下步驟配置JaCoCo Maven插件:

將JaCoCo Maven插件添加到我們的POM文件的插件部分。

  • 為單元測試配置代碼覆蓋率報告。
  • 配置代碼覆蓋率報告以進行集成測試。
    下面將更詳細地描述這些步驟。

將JaCoCo Maven插件添加到POM文件

通過將以下插件聲明添加到其“ 插件”部分,我們可以將JaCoCo Maven插件添加到我們的POM文件中:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.6.3.201306030806</version>
</plugin>

配置單元測試的代碼覆蓋率報告

我們可以通過將兩個執行添加到插件聲明中來為單元測試配置代碼覆蓋率報告。這些執行方式如下所述:

  • 第一次執行將創建一個指向JaCoCo運行時代理的屬性。確保執行數據已寫入文件target / coverage-reports / jacoco-ut.exec。將該屬性的名稱設置為surefireArgLine。運行單元測試時,此屬性的值作為VM參數傳遞。
  • 運行單元測試后,第二次執行將為單元測試創建代碼覆蓋率報告。確保從文件target / coverage-reports / jacoco-ut.exec中讀取執行數據,並將代碼覆蓋率報告寫入目錄target / site / jacoco-ut中。

我們的插件配置的相關部分如下所示:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.6.3.201306030806</version>
    <executions>
        <!--
           Prepares the property pointing to the JaCoCo runtime agent which
           is passed as VM argument when Maven the Surefire plugin is executed.
       -->
        <execution>
            <id>pre-unit-test</id>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
            <configuration>
                <!-- Sets the path to the file which contains the execution data. -->
                <destFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</destFile>
                <!--
                   Sets the name of the property containing the settings
                   for JaCoCo runtime agent.
               -->
                <propertyName>surefireArgLine</propertyName>
            </configuration>
        </execution>
        <!--
           Ensures that the code coverage report for unit tests is created after
           unit tests have been run.
       -->
        <execution>
            <id>post-unit-test</id>
            <phase>test</phase>
            <goals>
                <goal>report</goal>
            </goals>
            <configuration>
                <!-- Sets the path to the file which contains the execution data. -->
                <dataFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</dataFile>
                <!-- Sets the output directory for the code coverage report. -->
                <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

讓我們找出如何為集成測試配置代碼覆蓋率報告。

配置集成測試的代碼覆蓋率報告

我們可以通過在插件聲明中添加兩個執行來為集成測試配置代碼覆蓋率報告。這些執行方式如下所述:

  • 第一次執行將創建一個指向JaCoCo運行時代理的屬性。確保將執行數據寫入文件target / coverage-reports / jacoco-it.exec。將該屬性的名稱設置為failsafeArgLine。運行我們的集成測試時,此屬性的值作為VM參數傳遞。
  • 創建一個執行,該執行在集成測試運行後為集成測試創建代碼覆蓋率報告。確保從文件target / coverage-reports / jacoco-it.exec中讀取執行數據,並將代碼覆蓋率報告寫入目錄target / site / jacoco-it。

我們的插件配置的相關部分如下所示:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.6.3.201306030806</version>
    <executions>
        <!-- The Executions required by unit tests are omitted. -->
        <!--
           Prepares the property pointing to the JaCoCo runtime agent which
           is passed as VM argument when Maven the Failsafe plugin is executed.
       -->
        <execution>
            <id>pre-integration-test</id>
            <phase>pre-integration-test</phase>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
            <configuration>
                <!-- Sets the path to the file which contains the execution data. -->
                <destFile>${project.build.directory}/coverage-reports/jacoco-it.exec</destFile>
                <!--
                   Sets the name of the property containing the settings
                   for JaCoCo runtime agent.
               -->
                <propertyName>failsafeArgLine</propertyName>
            </configuration>
        </execution>
        <!--
           Ensures that the code coverage report for integration tests after
           integration tests have been run.
       -->
        <execution>
            <id>post-integration-test</id>
            <phase>post-integration-test</phase>
            <goals>
                <goal>report</goal>
            </goals>
            <configuration>
                <!-- Sets the path to the file which contains the execution data. -->
                <dataFile>${project.build.directory}/coverage-reports/jacoco-it.exec</dataFile>
                <!-- Sets the output directory for the code coverage report. -->
                <outputDirectory>${project.reporting.outputDirectory}/jacoco-it</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

現在,我們已經配置了JaCoCo Maven插件。下一步是配置Maven Surefire插件。讓我們找出如何做到這一點。

配置Maven Surefire插件

我們使用Maven Surefire插件運行示例應用程序的單元測試。因為我們要為單元測試創​​建代碼覆蓋率報告,所以我們必須確保在運行單元測試時JaCoCo代理正在運行。我們可以通過添加的價值保證本surefireArgLine財產作為價值argLine配置參數。

Maven Surefire插件的配置如下所示(突出显示了所需的更改):

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.15</version>
    <configuration>
        <!-- Sets the VM argument line used when unit tests are run. -->
        <argLine>${surefireArgLine}</argLine>
        <!-- Skips unit tests if the value of skip.unit.tests property is true -->
        <skipTests>${skip.unit.tests}</skipTests>
        <!-- Excludes integration tests when unit tests are run. -->
        <excludes>
            <exclude>**/IT*.java</exclude>
        </excludes>
    </configuration>
</plugin>

我們快完成了。剩下要做的就是配置Maven Failsafe插件。讓我們找出如何做到這一點。

配置Maven故障安全插件

我們的示例應用程序的集成測試由Maven Failsafe插件運行。因為我們要為集成測試創建代碼覆蓋率報告,所以我們必須確保在運行集成測試時JaCoCo代理正在運行。我們可以通過將failsafeArgLine屬性的值添加為argLine配置參數的值來實現。

Maven Failsafe插件的配置如下所示(突出显示了所需的更改):

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.15</version>
    <executions>
        <!--
            Ensures that both integration-test and verify goals of the Failsafe Maven
            plugin are executed.
        -->
        <execution>
            <id>integration-tests</id>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
            <configuration>
                <!-- Sets the VM argument line used when integration tests are run. -->
                <argLine>${failsafeArgLine}</argLine>
                <!--
                    Skips integration tests if the value of skip.integration.tests property
                    is true
                -->
                <skipTests>${skip.integration.tests}</skipTests>
            </configuration>
        </execution>
    </executions>
</plugin>

創建代碼覆蓋率報告

現在,我們已成功完成所需的配置。讓我們看看如何為單元測試和集成測試創建代碼覆蓋率報告。

此博客文章的示例應用程序具有三個構建配置文件,下面對此進行了描述:

  • 在開發配置文件開發過程中使用,這是我們構建的默認配置文件。當此配置文件處於活動狀態時,僅運行單元測試。
  • 在集成測試配置文件用於運行集成測試。
  • 在所有的測試配置文件用於為運行單元測試和集成測試。
    我們可以通過在命令提示符處運行以下命令來創建不同的代碼覆蓋率報告:

  • 命令mvn clean test運行單元測試,併為目錄target / site / jacoco-ut創建單元測試的代碼覆蓋率報告。
  • 命令mvn clean verify -P integration-test運行集成測試,併為目錄target / site / jacoco-it創建用於集成測試的代碼覆蓋率報告。
  • 命令mvn clean verify -P all-tests運行單元測試和集成測試,併為單元測試和集成測試創建代碼覆蓋率報告。

技術類文章精選

非技術文章精選

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理
【其他文章推薦】

※想知道網站建置、網站改版該如何進行嗎?將由專業工程師為您規劃客製化網頁設計及後台網頁設計

※不管是台北網頁設計公司、台中網頁設計公司,全省皆有專員為您服務

※Google地圖已可更新顯示潭子電動車充電站設置地點!!

※帶您來看台北網站建置,台北網頁設計,各種案例分享

※小三通物流營運型態?

※快速運回,大陸空運推薦?

016.Kubernetes二進制部署所有節點kube-proxy

一 部署 kube-proxy


kube-proxy 運行在所有節點上,它監聽 apiserver 中 service 和 endpoint 的變化情況,創建路由規則以提供服務 IP 和負載均衡功能。

1.1 安裝kube-proxy


提示:k8smaster01節點已下載相應二進制,可直接分發至node節點。

1.2 分發kube-proxy

  1 [root@k8smaster01 ~]# cd /opt/k8s/work
  2 [root@k8smaster01 work]# source /opt/k8s/bin/environment.sh
  3 [root@k8smaster01 work]# for all_ip in ${ALL_IPS[@]}
  4   do
  5     echo ">>> ${all_ip}"
  6     scp kubernetes/server/bin/kube-proxy root@${all_ip}:/opt/k8s/bin/
  7     ssh root@${all_ip} "chmod +x /opt/k8s/bin/*"
  8   done


1.3 創建kube-scheduler證書和私鑰

  1 [root@k8smaster01 ~]# cd /opt/k8s/work
  2 [root@k8smaster01 work]# cat > kube-proxy-csr.json <<EOF
  3 {
  4   "CN": "system:kube-proxy",
  5   "key": {
  6     "algo": "rsa",
  7     "size": 2048
  8   },
  9   "names": [
 10     {
 11       "C": "CN",
 12       "ST": "Shanghai",
 13       "L": "Shanghai",
 14       "O": "k8s",
 15       "OU": "System"
 16     }
 17   ]
 18 }
 19 EOF
 20 #創建kube-scheduler的CA證書請求文件



解釋:

  • CN:指定該證書的 User 為 system:kube-proxy;
  • 預定義的 RoleBinding system:node-proxier 將User system:kube-proxy 與 Role system:node-proxier 綁定,該 Role 授予了調用 kube-apiserver Proxy 相關 API 的權限;
  • 該證書只會被 kube-proxy 當做 client 證書使用,所以 hosts 字段為空。




  1 [root@k8smaster01 ~]# cd /opt/k8s/work
  2 [root@k8smaster01 work]# cfssl gencert -ca=/opt/k8s/work/ca.pem \
  3 -ca-key=/opt/k8s/work/ca-key.pem -config=/opt/k8s/work/ca-config.json \
  4 -profile=kubernetes kube-proxy-csr.json | cfssljson -bare kube-proxy		#生成CA密鑰(ca-key.pem)和證書(ca.pem)


1.4 創建和分發kubeconfig


kube-proxy 使用 kubeconfig 文件訪問 apiserver,該文件提供了 apiserver 地址、嵌入的 CA 證書和 kube-proxy 證書:

  1 [root@k8smaster01 ~]# cd /opt/k8s/work
  2 [root@k8smaster01 work]# source /opt/k8s/bin/environment.sh
  3 [root@k8smaster01 work]# kubectl config set-cluster kubernetes \
  4   --certificate-authority=/opt/k8s/work/ca.pem \
  5   --embed-certs=true \
  6   --server=${KUBE_APISERVER} \
  7   --kubeconfig=kube-proxy.kubeconfig
  8 
  9 [root@k8smaster01 work]# kubectl config set-credentials kube-proxy \
 10   --client-certificate=kube-proxy.pem \
 11   --client-key=kube-proxy-key.pem \
 12   --embed-certs=true \
 13   --kubeconfig=kube-proxy.kubeconfig
 14 
 15 [root@k8smaster01 work]# kubectl config set-context default \
 16   --cluster=kubernetes \
 17   --user=kube-proxy \
 18   --kubeconfig=kube-proxy.kubeconfig
 19 
 20 [root@k8smaster01 work]# kubectl config use-context default --kubeconfig=kube-proxy.kubeconfig
 21 
 22 [root@k8smaster01 ~]# cd /opt/k8s/work
 23 [root@k8smaster01 work]# source /opt/k8s/bin/environment.sh
 24 [root@k8smaster01 work]# for node_name in ${NODE_NAMES[@]}
 25   do
 26     echo ">>> ${node_name}"
 27     scp kube-proxy.kubeconfig root@${node_name}:/etc/kubernetes/
 28   done


1.5 創建kube-proxy 配置文件


從 v1.10 開始,kube-proxy 部分參數可以配置文件中配置。可以使用 –write-config-to 選項生成該配置文件。

  1 [root@k8smaster01 ~]# cd /opt/k8s/work
  2 [root@k8smaster01 work]# cat > kube-proxy-config.yaml.template <<EOF
  3 kind: KubeProxyConfiguration
  4 apiVersion: kubeproxy.config.k8s.io/v1alpha1
  5 clientConnection:
  6   burst: 200
  7   kubeconfig: "/etc/kubernetes/kube-proxy.kubeconfig"
  8   qps: 100
  9 bindAddress: ##ALL_IP##
 10 healthzBindAddress: ##ALL_IP##:10256
 11 metricsBindAddress: ##ALL_IP##:10249
 12 enableProfiling: true
 13 clusterCIDR: ${CLUSTER_CIDR}
 14 hostnameOverride: ##ALL_NAME##
 15 mode: "ipvs"
 16 portRange: ""
 17 kubeProxyIPTablesConfiguration:
 18   masqueradeAll: false
 19 kubeProxyIPVSConfiguration:
 20   scheduler: rr
 21   excludeCIDRs: []
 22 EOF



解釋:

  • bindAddress: 監聽地址;
  • clientConnection.kubeconfig: 連接 apiserver 的 kubeconfig 文件;
  • clusterCIDR: kube-proxy 根據 –cluster-cidr 判斷集群內部和外部流量,指定 –cluster-cidr 或 –masquerade-all 選項后 kube-proxy 才會對訪問 Service IP 的請求做 SNAT;
  • hostnameOverride: 參數值必須與 kubelet 的值一致,否則 kube-proxy 啟動後會找不到該 Node,從而不會創建任何 ipvs 規則;
  • mode: 使用 ipvs 模式。

1.6 分發配置文件

  1 [root@k8smaster01 ~]# cd /opt/k8s/work
  2 [root@k8smaster01 work]# source /opt/k8s/bin/environment.sh
  3 [root@k8smaster01 work]# for (( i=0; i < 6; i++ ))
  4   do
  5     echo ">>> ${ALL_NAMES[i]}"
  6     sed -e "s/##ALL_NAME##/${ALL_NAMES[i]}/" -e "s/##ALL_IP##/${ALL_IPS[i]}/" kube-proxy-config.yaml.template > kube-proxy-config-${ALL_NAMES[i]}.yaml.template
  7     scp kube-proxy-config-${ALL_NAMES[i]}.yaml.template root@${ALL_NAMES[i]}:/etc/kubernetes/kube-proxy-config.yaml
  8   done


1.7 創建kube-proxy的systemd

  1 [root@k8smaster01 ~]# cd /opt/k8s/work
  2 [root@k8smaster01 work]# source /opt/k8s/bin/environment.sh
  3 [root@k8smaster01 work]# cat > kube-proxy.service <<EOF
  4 [Unit]
  5 Description=Kubernetes Kube-Proxy Server
  6 Documentation=https://github.com/GoogleCloudPlatform/kubernetes
  7 After=network.target
  8 
  9 [Service]
 10 WorkingDirectory=${K8S_DIR}/kube-proxy
 11 ExecStart=/opt/k8s/bin/kube-proxy \\
 12   --config=/etc/kubernetes/kube-proxy-config.yaml \\
 13   --logtostderr=true \\
 14   --v=2
 15 Restart=on-failure
 16 RestartSec=5
 17 LimitNOFILE=65536
 18 
 19 [Install]
 20 WantedBy=multi-user.target
 21 EOF


1.8 分發kube-proxy systemd

  1 [root@k8smaster01 ~]# cd /opt/k8s/work
  2 [root@k8smaster01 work]# source /opt/k8s/bin/environment.sh
  3 [root@k8smaster01 work]# for all_name in ${ALL_NAMES[@]}
  4   do
  5     echo ">>> ${all_name}"
  6     scp kube-proxy.service root@${all_name}:/etc/systemd/system/
  7   done						#分發system


二 啟動並驗證

2.1 啟動kube-proxy 服務

  1 [root@k8smaster01 ~]# cd /opt/k8s/work
  2 [root@k8smaster01 work]# source /opt/k8s/bin/environment.sh
  3 [root@k8smaster01 work]# for all_ip in ${ALL_IPS[@]}
  4   do
  5     echo ">>> ${all_ip}"
  6     ssh root@${all_ip} "mkdir -p ${K8S_DIR}/kube-proxy"
  7     ssh root@${all_ip} "modprobe ip_vs_rr"
  8     ssh root@${all_ip} "systemctl daemon-reload && systemctl enable kube-proxy && systemctl restart kube-proxy"
  9   done						#啟動服務前必須先創建工作目錄


2.2 檢查kube-proxy 服務

  1 [root@k8smaster01 ~]# source /opt/k8s/bin/environment.sh
  2 [root@k8smaster01 ~]# for all_ip in ${ALL_IPS[@]}
  3   do
  4     echo ">>> ${all_ip}"
  5     ssh root@${all_ip} "systemctl status kube-proxy|grep Active"
  6   done


2.3 查看監聽端口


kube-proxy 監聽 10249 和 10256 端口:

  • 10249:對外提供 /metrics;
  • 10256:對外提供 /healthz 的訪問。

  1 [root@k8smaster01 ~]# cd /opt/k8s/work
  2 [root@k8smaster01 work]# source /opt/k8s/bin/environment.sh
  3 [root@k8smaster01 work]# for all_ip in ${ALL_IPS[@]}
  4   do
  5     echo ">>> ${all_ip}"
  6     ssh root@${all_ip} "sudo netstat -lnpt|grep kube-prox"
  7   done



2.4 查看ipvs 路由規則

  1 [root@k8smaster01 ~]# cd /opt/k8s/work
  2 [root@k8smaster01 work]# source /opt/k8s/bin/environment.sh
  3 [root@k8smaster01 work]# for all_ip in ${ALL_IPS[@]}
  4   do
  5     echo ">>> ${all_ip}"
  6     ssh root@${all_ip} "/usr/sbin/ipvsadm -ln"
  7   done



可見所有通過 https 訪問 K8S SVC kubernetes 的請求都轉發到 kube-apiserver 節點的 6443 端口。本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理
【其他文章推薦】

※USB CONNECTOR掌控什麼技術要點? 帶您認識其相關發展及效能

※評比前十大台北網頁設計、台北網站設計公司知名案例作品心得分享

※智慧手機時代的來臨,RWD網頁設計已成為網頁設計推薦首選

※台灣海運大陸貨務運送流程

※兩岸物流進出口一站式服務

Kubernetes概述

1. Kubernetes是什麼

Kubernetes是一個可移植的、可擴展的、用於管理容器化工作負載和服務的開源平台,它簡化(促進)了聲明式配置和自動化。它有一個龐大的、快速增長的生態系統。Kubernetes的服務、支持和工具隨處可見。

Kubernetes一詞源於希臘語,意為舵手或飛行員。2014年,谷歌開放了Kubernetes項目的源代碼。Kubernetes基於谷歌在大規模運行生產工作負載方面的15年經驗,以及來自社區的最佳想法和實踐。

使用 Kubernetes, 我們可以快速高效地響應客戶需求:

  • 快速、可預測地部署你的應用程序
  • 擁有即時擴展應用程序的能力
  • 不影響現有業務的情況下,無縫地發布新功能
  • 優化硬件資源,降低成本

Kubernetes的目標是構建一個軟件和工具的生態系統,以減輕你在公共雲或私有雲運行應用程序的負擔。

1.1. 時光倒流

讓我們把時間回溯到從前,看看為什麼Kubernetes是如此有用。

傳統部署時代:在早期,組織在物理服務器上運行應用程序。無法為物理服務器中的應用程序定義資源邊界,這導致了資源分配問題。例如,如果一個物理服務器上運行多個應用程序,那麼在某些情況下,一個應用程序將佔用大部分資源,從而導致其他應用程序性能下降。對此的解決方案是在不同的物理服務器上運行每個應用程序。但是,由於資源沒有得到充分利用,而且維護許多物理服務器的成本很高,所以無法進行擴展。

虛擬化部署時代:作為一種解決方案,引入了虛擬化。它允許你在單個物理服務器的CPU上運行多個虛擬機(vm)。虛擬化允許在vm之間隔離應用程序,並提供一定程度的安全性,因為一個應用程序的信息不能被另一個應用程序自由訪問。

虛擬化可以更好地利用物理服務器中的資源,並提供更好的可伸縮性,因為可以方便地添加或更新應用程序,從而降低硬件成本,等等。通過虛擬化,你可以將一組物理資源表示為一次性虛擬機集群。

每個VM是一個完整的機器,運行所有組件,包括它自己的操作系統,運行在虛擬硬件之上。

容器部署時代:容器類似於vm,但是它們具有寬鬆的隔離屬性,以便在應用程序之間共享操作系統(OS)。因此,容器被認為是輕量級的。與VM類似,容器有自己的文件系統、CPU、內存、進程空間等等。由於它們與底層基礎設施解耦,因此可以跨雲和OS發行版移植。

容器已經變得很流行,因為它們提供了額外的好處,比如:

  • 敏捷應用程序創建和部署:與使用VM鏡像相比,增加了容器鏡像創建的方便性和效率
  • 持續開發、集成和部署:提供可靠且頻繁的容器鏡像構建和部署,具有快速且輕鬆的回滾
  • 開發和運維關注點分離:在構建/發布時而不是部署時創建應用程序容器鏡像,從而將應用程序與基礎設施分離
  • 可觀察性:不僅能显示操作系統級的信息和指標,還能显示應用程序的健康狀況和其他信號
  • 跨開發、測試和生產的環境一致性:在筆記本電腦上運行與在雲上運行完全相同
  • 雲和操作系統發布的可移植性:運行在Ubuntu, RHEL, CoreOS, on-prem,谷歌Kubernetes引擎,和其他任何地方
  • 以應用程序為中心的管理:將抽象級別從在虛擬硬件上運行操作系統提高到使用邏輯資源在操作系統上運行應用程序
  • 鬆散耦合、分佈式、彈性、解放的微服務:應用程序被分解成更小的獨立部分,可以動態地部署和管理——而不是運行在一台大型單用途機器上的單片堆棧
  • 資源隔離:可預測的應用程序性能
  • 資源利用:效率高,密度大 

1.2. 為什麼需要Kubernetes?它能做什麼?

容器是捆綁和運行應用程序的好方法。在生產環境中,你需要管理運行應用程序的容器,並確保沒有停機時間。例如,如果一個容器發生故障,則需要啟動另一個容器。如果這個行為由一個系統來處理不是更容易嗎?

Kubernetes為你提供了一個能夠彈性地運行分佈式系統的框架。它負責處理應用程序的擴展和故障轉移,提供部署模式,等等。

Kubernetes為你提供:

服務發現和負載平衡

  Kubernetes可以使用DNS名稱或自己的IP地址公開容器。如果到容器的通信量很高,Kubernetes能夠實現負載平衡並分配網絡通信量,從而使部署保持穩定

存儲編排

  Kubernetes允許你自動掛載自己選擇的存儲系統,比如本地存儲、公有雲提供商等等

自動滾動更新和回滾

  可以使用Kubernetes描述所部署容器的期望狀態,並且可以以受控的速率將實際狀態更改為期望狀態

自動包裝

  你只需為Kubernetes提供一組節點,它便可以使用這些節點來運行容器化的任務。告訴Kubernetes每個容器需要多少CPU和內存(RAM)。Kubernetes可以在你的節點上放置容器,以充分利用你的資源。 

自動重啟 

  Kubernetes會重新啟動失敗的容器,替換容器,殺死不響應用戶定義的健康檢查的容器,並且在它們準備好服務之前不會將他們暴露給客戶端。

秘密和配置管理

  Kubernetes允許你存儲和管理敏感信息,比如密碼、OAuth令牌和ssh密鑰。你可以部署和更新秘密和應用程序配置,而無需重新構建容器映像,也無需在堆棧配置中公開秘密。 

1.3. Kubernetes不是什麼

Kubernetes不是一個傳統的、包羅萬象的PaaS(平台即服務)系統。由於Kubernetes是在容器級別而不是在硬件級別操作的,所以它提供了一些PaaS產品常見的通用特性,例如部署、擴展、負載平衡、日誌記錄和監視。但是,Kubernetes不是單片的,這些默認的解決方案是可選的和可插拔的。Kubernetes為構建開發人員平台提供了構建塊,但是在重要的地方保留了用戶的選擇和靈活性。

  • 不限制所支持的應用程序類型。Kubernetes的目標是支持非常多樣化的工作負載,包括無狀態、有狀態和數據處理工作負載。如果一個應用程序可以在容器中運行,那麼它應該可以在Kubernetes上運行。
  • 不部署源代碼,也不構建應用程序。持續集成、交付和部署(CI/CD)工作流由組織文化和偏好以及技術需求決定。
  • 不提供應用級服務,如中間件(例如消息總線)、數據處理框架(例如Spark)、數據庫(例如mysql)、緩存,也不提供集群存儲系統(例如Ceph)作為內置服務。這些組件可以運行在Kubernetes上,並且/或者可以由運行在Kubernetes上的應用程序通過可移植的機制(如Open Service Broker)訪問。
  • Kubernetes 允許用戶選擇其他的日誌記錄,監控和告警系統 
  • 不提供也不強制要求配置語言/系統(例如,jsonnet)。它提供了一個聲明性API,可以被任意形式的聲明性規範作為目標。
  • 不提供也不採用任何全面的機器配置、維護、管理或自修復系統。
  • 此外,Kubernetes不僅僅是一個編排系統。事實上,它消除了對編排的需要。編排的技術定義是執行一個已定義的工作流:首先執行a,然後執行B,然後執行c。相反,Kubernetes包括一套獨立、可組合的控制過程,通過聲明式語法使其連續地朝着期望狀態驅動當前狀態。你怎麼從A點到c點都不重要,只要告訴到C的狀態即可。 

2. Kubernetes組件

當你部署Kubernetes的時候,你會得到一個集群。

一個集群是一組機器,稱為節點(nodes),它們運行由Kubernetes管理的容器化應用程序。

一個集群至少有一個工作節點(worker node)和一個主節點(master node)。

工作節點承載應用程序的組件。主節點管理集群中的工作節點和pods。多個主節點用於提供具有故障轉移和高可用性的集群。

下面是Kubernetes集群的關係圖: 

2.1. Master組件

Master組件提供集群的控制面板。Master組件對集群做出全局決策(例如,調度),Master組件檢測並響應集群事件(例如,當部署的replicas字段不滿足時啟動一個新的pod)

Master組件可以在集群中的任何機器上運行。但是,為了簡單起見,設置腳本通常在同一台機器上啟動所有Master組件,並且不在這台機器上運行用戶容器。

kube-apiserver 

  API服務器是一個Kubernetes面板控制組件,用於公開Kubernetes API。它是Kubernetes控制面板的前端。

  Kubernetes API服務器的主要實現是kube-apiserver。kube-apiserver被設計成水平伸縮——也就是說,它通過部署更多實例來伸縮。你可以運行kube-apiserver的多個實例,並在這些實例之間平衡流量。

etcd 

  一致性和高可用的鍵值存儲用作Kubernetes的所有集群數據備份存儲。

  如果你的Kubernetes集群使用etcd作為其備份存儲,請確保對這些數據有備份計劃。

kube-scheduler

  監視沒有分配節點的新創建的pod,併為它們選擇要運行的節點。 

kube-controller-manager

  運行控制器的組件,從邏輯上講,每個控制器都是一個單獨的進程,但是為了降低複雜性,它們都被編譯成一個單一的二進制文件,並在一個進程中運行。

這些控制器包括:

  • Node Controller:節點控制器負責發現和響應節點故障
  • Replication Controller:副本控制器負責為系統中的每個副本控制器對象維護正確的pod數量
  • Endpoints Controller:端點控制器填充端點對象(即,連接服務和pod)
  • Service Account & Token Controllers:為新的名稱空間創建默認帳戶和API訪問令牌 

cloud-controller-manager 

  雲控制器-管理器,運行與底層雲提供商交互的控制器

2.2. Node組件

Node組件在每個節點上運行,維護運行的pods並提供Kubernetes運行時環境。 

kubelet

  kubelet是一個代理,它運行在集群中的每個節點上,它確保容器在一個pod中運行。kubelet只管理由Kubernetes創建的容器。 

kube-proxy

  kube-proxy是運行在集群中每個節點上的網絡代理,是實現Kubernetes服務概念的一部分。

  kube-proxy維護節點上的網絡規則。這些網絡規則允許從集群內外的網絡會話與pod進行網絡通信。

  如果有可用的操作系統包過濾層,kube-proxy將使用它。否則,kube-proxy將轉發流量本身。

Container Runtime

  容器運行時是負責運行容器的軟件。

  Kubernetes支持多個容器運行時:Docker、containerd、crio、rktlet和Kubernetes CRI(容器運行時接口)的任何實現。 

2.3. Addons(插件)

DNS

  雖然其他插件不是嚴格要求的,但所有Kubernetes集群都應該有集群DNS,因為許多示例都依賴於它。

Web UI (Dashboard)

  Dashboard是一個通用的、基於web的Kubernetes集群用戶界面。它允許用戶管理和排除集群中運行的應用程序和集群本身的故障。

Container Resource Monitoring

  容器資源監控記錄中央數據庫中容器的一般時間序列指標,並提供用於瀏覽該數據的UI。

Cluster-level Logging

  集群級別的日誌記錄機制負責將容器日誌保存到具有搜索/瀏覽界面的中央日誌存儲中。

3. 回顧&小結

Kubernetes:

  • 可移植: 無論公有雲、私有雲、混合雲還是多雲架構都全面支持
  • 可擴展: 它是模塊化、可插拔、可掛載、可組合的,支持各種形式的擴展
  • 自修復: 它可以自保持應用狀態、可自重啟、自複製、自縮放的,通過聲明式語法提供了強大的自修復能力

Kubernetes建立在Google公司15年的運維經驗基礎之上,Google所有的應用都運行在容器上 

 

 

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理
【其他文章推薦】

※想知道網站建置、網站改版該如何進行嗎?將由專業工程師為您規劃客製化網頁設計及後台網頁設計

※不管是台北網頁設計公司、台中網頁設計公司,全省皆有專員為您服務

※Google地圖已可更新顯示潭子電動車充電站設置地點!!

※帶您來看台北網站建置,台北網頁設計,各種案例分享

※小三通物流營運型態?

※快速運回,大陸空運推薦?

初識web API接口及Restful接口規範

一、web API接口

什麼是web API接口?:

明確了請求方式,提供對應後台所需參數,請求url鏈接可以得到後台的響應數據
url : 返回數據的url

請求方式:
get,post,put,patch….

請求參數:json或xml格式的key-value類型數據

  • ak:6E823f587c95f0148c19993539b99295
  • region:上海
  • query:肯德基
  • output:json

響應結果:
​ 返回json或xml格式的key-value類型數據

  • 上方請求參數的output參數值決定了響應數據的格式

  • {
        "status":0,
        "message":"ok",
        "results":[
            {
                "name":"肯德基(羅餐廳)",
                "location":{
                    "lat":31.415354,
                    "lng":121.357339
                },
                "address":"月羅路2380號",
                "province":"上海市",
                "city":"上海市",
                "area":"寶山區",
                "street_id":"339ed41ae1d6dc320a5cb37c",
                "telephone":"(021)56761006",
                "detail":1,
                "uid":"339ed41ae1d6dc320a5cb37c"
            }
            ...
            ]
    }

怎麼寫接口?:

​ 參照某種規則(規範)書寫url鏈接,同時根據規則制定請求方式,請求數據與響應結果

接口文檔:

​ 提供給前後台開發人員與測試人員查看

接口工具:

YAPI平台

​ 專門寫接口文檔的YAPI平台

​ YApi是去哪兒網的前端技術中心的一個開源可視化接口管理平台。

​

  • 創建接口項目
  • 創建接口
  • 編寫接口

接口測試工具:Postman

Postman是一款接口調試工具,是一款免費的可視化軟件,同時支持各種操作系統平台,是測試接口的首選工具。

Postman可以直接從下載獲得,然後進行傻瓜式安裝。

  • 工作面板
  • 簡易的get請求
  • 簡易的post請求
  • 案例:請求百度地圖接口

接口規範:

​ webapi接口規範:restful
​

RESTful API介紹

RESTful介紹

REST與技術無關,代表的是一種軟件架構風格,REST是Representational State Transfer的簡稱,中文翻譯為“表徵狀態轉移”或“表現層狀態轉化”。

推薦閱讀

RESTful API設計指南

推薦閱讀

API與用戶的通信協議

總是使用。

域名

用api關鍵字來標識接口url

注:看到api字眼,就代表該請求url鏈接是完成前後台數據交互的

版本

\1. 將版本信息放在URL中,如:

​

​

​ v1,v2代表不同數據版本的提現,前提是一種數據資源有多個版本

\2. 將版本信息放在請求頭中。

url路徑

視網絡上任何東西都是資源,均使用名詞表示(一般為複數形式)

在url鏈接中獎勵不要出現操作資源的動詞

​ 錯誤示範:

特殊的接口可以出現動詞,因為這些接口一般沒有一個明確的資源,或是動詞就是接口的核心含義

method請求方式

GET :從服務器取出資源(一項或多項)

POST :在服務器新建一個資源

PUT :在服務器更新資源(客戶端提供改變后的完整資源)

PATCH :在服務器更新資源(客戶端提供改變的屬性)

DELETE :從服務器刪除資源

過濾

通過在url上傳參的形式傳遞搜索條件

狀態碼

200 OK - [GET]:服務器成功返回用戶請求的數據,該操作是冪等的(Idempotent)。
201 CREATED - [POST/PUT/PATCH]:用戶新建或修改數據成功。
202 Accepted - [*]:表示一個請求已經進入後台排隊(異步任務)
204 NO CONTENT - [DELETE]:用戶刪除數據成功。


301:永久重定向
302:暫時重定向


400 INVALID REQUEST - [POST/PUT/PATCH]:用戶發出的請求有錯誤,服務器沒有進行新建或修改數據的操作,該操作是冪等的。
401 Unauthorized - [*]:表示用戶沒有權限(令牌、用戶名、密碼錯誤)。
403 Forbidden - [*] 表示用戶得到授權(與401錯誤相對),但是訪問是被禁止的。
404 NOT FOUND - [*]:用戶發出的請求針對的是不存在的記錄,服務器沒有進行操作,該操作是冪等的。
406 Not Acceptable - [GET]:用戶請求的格式不可得(比如用戶請求JSON格式,但是只有XML格式)。
410 Gone -[GET]:用戶請求的資源被永久刪除,且不會再得到的。
422 Unprocesable entity - [POST/PUT/PATCH] 當創建一個對象時,發生一個驗證錯誤。


500 INTERNAL SERVER ERROR - [*]:服務器發生錯誤,用戶將無法判斷髮出的請求是否成功。

錯誤處理

狀態碼是4xx時,應返回錯誤信息,error當做key。    

{
    error: "Invalid API key"
}

返回結果

針對不同操作,服務器向用戶返回的結果應該符合以下規範

GET     /collection:返回資源對象的列表(數組)
GET     /collection/resource:返回單個資源對象
POST    /collection:返回新生成的資源對象
PUT     /collection/resource:返回完整的資源對象
PATCH   /collection/resource:返回完整的資源對象
DELETE  /collection/resource:返回一個空文檔
{
    "status": 0,
    "msg": "ok",
    "results":[
        {
            "name":"肯德基(羅餐廳)",
            "location":{
                "lat":31.415354,
                "lng":121.357339
            },
            "address":"月羅路2380號",
            "province":"上海市",
            "city":"上海市",
            "area":"寶山區",
            "street_id":"339ed41ae1d6dc320a5cb37c",
            "telephone":"(021)56761006",
            "detail":1,
            "uid":"339ed41ae1d6dc320a5cb37c"
        }
        ...
        ]
}

Hypermedia API

RESTful API最好做到Hypermedia,即返回結果中提供鏈接,連向其他API方法,使得用戶不查文檔,也知道下一步應該做什麼。

{"link": {
  "rel":   "collection https://www.example.com/zoos",
  "href":  "https://api.example.com/zoos",
  "title": "List of zoos",
  "type":  "application/vnd.yourformat+json"
}}

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理
【其他文章推薦】

※USB CONNECTOR掌控什麼技術要點? 帶您認識其相關發展及效能

※評比前十大台北網頁設計、台北網站設計公司知名案例作品心得分享

※智慧手機時代的來臨,RWD網頁設計已成為網頁設計推薦首選

※台灣海運大陸貨務運送流程

※兩岸物流進出口一站式服務