分类:容器技术

一看必会系列:kubernetes使用yaml部署nginx集群

注意空行和格式

 

1 创建nginx-rc.yaml

vim "nginx-rc.yaml" 18L, 350C       

apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx-controller
spec:
  replicas: 2
  selector:
    name: nginx-selector
  template:
    metadata:
      labels:
        name: nginx-selector
    spec:
      containers:
        – name: nginx
          image: 192.168.142.131:5000/nginx:v1
          ports:
            – containerPort: 80

2 创建nginx-service-nodeport.yaml

vim nginx-service-nodeport.yaml

apiVersion: v1
kind: Service
metadata:
  name: nginx-service-nodeport
spec:
  ports:
    – port: 8800
      targetPort: 80
      protocol: TCP
  type: NodePort
  selector:
    name: nginx-selector

~                                                                                      
3 创建pod

kubectl create -f nginx-rc.yaml

4 创建service
kubectl create -f nginx-service-nodeport.yaml

 

看RC状态                                             

[root@centos011 ~]# kubectl get rc
NAME               DESIRED   CURRENT   READY     AGE
nginx-controller   2         2         2         26m    2个是正常

------中间广告---------

 

看service 状态
[root@centos011 ~]# kubectl get service
NAME                       CLUSTER-IP        EXTERNAL-IP   PORT(S)          AGE
my-nginx-974504764-z1zwq   192.168.142.107   <pending>     80:32594/TCP     17h
my-nginx-974504764-z3mtw   192.168.142.252   <pending>     80:30025/TCP     17h
nginx-service-nodeport     192.168.142.53    <nodes>       8800:30572/TCP   26m  service 状态 8800映射到30672

 

看nodeport可对外提供服务的端口

[root@centos011 ~]# kubectl describe service nginx-service-nodeport
Name:            nginx-service-nodeport
Namespace:        default
Labels:            <none>
Selector:        name=nginx-selector
Type:            NodePort
IP:            192.168.142.53
Port:            <unset>    8800/TCP             提供service端口
NodePort:        <unset>   30572/TCP    外部能访问的端口
Endpoints:        172.17.100.2:80,172.17.73.2:80  容器内部端口
Session Affinity:    None
No events.
[root@centos011 ~]#

更详细的

[root@centos011 ~]# kubectl get pods –all-namespaces -o wide
NAMESPACE     NAME                                    READY     STATUS    RESTARTS   AGE       IP             NODE
default       nginx-controller-mcm0s                  1/1       Running   0          28m       172.17.100.2   192.168.142.132
default       nginx-controller-vq0dl                  1/1       Running   0          28m       172.17.73.2    192.168.142.130
kube-system   kubernetes-dashboard-3820983789-jnsdz   1/1       Running   0          18h       172.17.88.3    192.168.142.131
[root@centos011 ~]#

 

访问方式

http://192.168.142.131:30572/

http://192.168.142.130:30572/

因为service使用的是NodePort方式,所以在任何一个节点访问31152这个端口都可以访问nginx

image

https://www.cnblogs.com/puroc/p/5764330.html

一看就会系列:kubernetes使用yaml部署nginx集群

注意空行和格式

 

1 创建nginx-rc.yaml

vim "nginx-rc.yaml" 18L, 350C       

apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx-controller
spec:
  replicas: 2
  selector:
    name: nginx-selector
  template:
    metadata:
      labels:
        name: nginx-selector
    spec:
      containers:
        – name: nginx
          image: 192.168.142.131:5000/nginx:v1
          ports:
            – containerPort: 80

2 创建nginx-service-nodeport.yaml

vim nginx-service-nodeport.yaml

apiVersion: v1
kind: Service
metadata:
  name: nginx-service-nodeport
spec:
  ports:
    – port: 8800
      targetPort: 80
      protocol: TCP
  type: NodePort
  selector:
    name: nginx-selector

~                                                                                      
3 创建pod

kubectl create -f nginx-rc.yaml

4 创建service
kubectl create -f nginx-service-nodeport.yaml

 

看RC状态                                             

[root@centos011 ~]# kubectl get rc
NAME               DESIRED   CURRENT   READY     AGE
nginx-controller   2         2         2         26m    2个是正常

 

看service 状态
[root@centos011 ~]# kubectl get service
NAME                       CLUSTER-IP        EXTERNAL-IP   PORT(S)          AGE
my-nginx-974504764-z1zwq   192.168.142.107   <pending>     80:32594/TCP     17h
my-nginx-974504764-z3mtw   192.168.142.252   <pending>     80:30025/TCP     17h
nginx-service-nodeport     192.168.142.53    <nodes>       8800:30572/TCP   26m  service 状态 8800映射到30672

 

看nodeport可对外提供服务的端口

[root@centos011 ~]# kubectl describe service nginx-service-nodeport
Name:            nginx-service-nodeport
Namespace:        default
Labels:            <none>
Selector:        name=nginx-selector
Type:            NodePort
IP:            192.168.142.53
Port:            <unset>    8800/TCP             提供service端口
NodePort:        <unset>   30572/TCP    外部能访问的端口
Endpoints:        172.17.100.2:80,172.17.73.2:80  容器内部端口
Session Affinity:    None
No events.
[root@centos011 ~]#

更详细的

[root@centos011 ~]# kubectl get pods –all-namespaces -o wide
NAMESPACE     NAME                                    READY     STATUS    RESTARTS   AGE       IP             NODE
default       nginx-controller-mcm0s                  1/1       Running   0          28m       172.17.100.2   192.168.142.132
default       nginx-controller-vq0dl                  1/1       Running   0          28m       172.17.73.2    192.168.142.130
kube-system   kubernetes-dashboard-3820983789-jnsdz   1/1       Running   0          18h       172.17.88.3    192.168.142.131
[root@centos011 ~]#

 

访问方式

http://192.168.142.131:30572/

http://192.168.142.130:30572/

因为service使用的是NodePort方式,所以在任何一个节点访问31152这个端口都可以访问nginx

 

https://www.cnblogs.com/puroc/p/5764330.html

kubernetes deployments部署容器测试

有弊病,NODE上端口是不一致的。玩玩而已。

 

端口映射过程

 

endpoing—service —–nodeport—-可被外访问

容器内部端口–服务端口–真正的端口

跑多POD容器
kubectl run my-nginx –image=192.168.142.131:5000/nginx:v1 –replicas=2 –port=80

查看状态
[root@centos011 ~]# kubectl get pods
NAME                       READY     STATUS    RESTARTS   AGE
my-nginx-974504764-z1zwq   1/1       Running   1          32m
my-nginx-974504764-z3mtw   1/1       Running   0          32m
[root@centos011 ~]#

开启外网访问

[root@centos011 ~]# kubectl expose pod my-nginx-974504764-z3mtw –port=80 –type=LoadBalancer
service "my-nginx-974504764-z3mtw" exposed
[root@centos011 ~]# kubectl get services
NAME                       CLUSTER-IP        EXTERNAL-IP   PORT(S)        AGE
kubernetes                 192.168.142.1     <none>        443/TCP        6h
my-nginx-974504764-z1zwq   192.168.142.107   <pending>     80:32594/TCP   6m
my-nginx-974504764-z3mtw   192.168.142.252   <pending>     80:30025/TCP   5s
[root@centos011 ~]#

查看状态
root@centos011 ~]# kubectl get svc
NAME                       CLUSTER-IP        EXTERNAL-IP   PORT(S)        AGE
kubernetes                 192.168.142.1     <none>        443/TCP        6h
my-nginx-974504764-z1zwq   192.168.142.107   <pending>     80:32594/TCP   11m  后面是主机端口
my-nginx-974504764-z3mtw   192.168.142.252   <pending>     80:30025/TCP   4m

相看nodeIP
kubectl get pods –all-namespaces -o wide

访问
http://192.168.142.132:32594/

删除 deployments

[root@centos011 ~]# kubectl delete deployments my-nginx
deployment "my-nginx" deleted
[root@centos011 ~]#

一看必会系列:kubernetes 正确的删除pod的方式

查看所有pods

[root@centos011 ~]# kubectl get pods
NAME                          READY     STATUS              RESTARTS   AGE
jeffnginx-946323625-6bjz8     1/1       Running             0          46s
jeffnginx1-3759915275-fbv90   0/1       ContainerCreating   0          21h
jeffnginx2-521453951-5r0g4    0/1       ContainerCreating   0          21h
nginx-controller-7bxpx        0/1       ContainerCreating   0          21h
nginx-controller-fl3kf        0/1       ContainerCreating   0          21h

用delete一个一个删除
[root@centos011 ~]# kubectl delete pods jeffnginx1-3759915275-fbv90
pod "jeffnginx1-3759915275-fbv90" deleted
[root@centos011 ~]# kubectl delete pods jeffnginx2-521453951-5r0g4
pod "jeffnginx2-521453951-5r0g4" deleted
[root@centos011 ~]# kubectl delete pods nginx-controller-7bxpx
pod "nginx-controller-7bxpx" deleted
[root@centos011 ~]# kubectl delete pods nginx-controller-fl3kf
pod "nginx-controller-fl3kf" deleted
[root@centos011 ~]#

发现所有pod会自己起来这是repolic 的机制很正确。这是正是确保replicas为1的动作。

[root@centos011 ~]# kubectl get pods
NAME                          READY     STATUS              RESTARTS   AGE
jeffnginx-946323625-6bjz8     1/1       Running             0          1m
jeffnginx1-3759915275-v5791   1/1       Running             0          47s
jeffnginx2-521453951-hgc8z    0/1       ContainerCreating   0          37s
nginx-controller-l67nm        0/1       ImagePullBackOff    0          30s
nginx-controller-pmrxf        0/1       ContainerCreating   0          22s

[root@centos011 ~]# kubectl get pods
NAME                          READY     STATUS              RESTARTS   AGE
jeffnginx-946323625-6bjz8     1/1       Running             0          3m
jeffnginx1-3759915275-v5791   1/1       Running             0          2m
jeffnginx2-521453951-hgc8z    0/1       ContainerCreating   0          1m
nginx-controller-l67nm        0/1       ErrImagePull        0          1m
nginx-controller-pmrxf        0/1       ContainerCreating   0          1m

使用deployments 命令

[root@centos011 ~]# kubectl get deployments
NAME         DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
jeffnginx    1         1         1            1           23h
jeffnginx1   1         1         1            1           22h
jeffnginx2   1         1         1            0           22h
[root@centos011 ~]# kubectl delete deployment jeffnginx
deployment "jeffnginx" deleted
[root@centos011 ~]# kubectl delete deployment jeffnginx1
deployment "jeffnginx1" deleted
[root@centos011 ~]# kubectl delete deployment jeffnginx2
deployment "jeffnginx2" deleted

删除后pods将不在存在
[root@centos011 ~]# kubectl get deployments
No resources found.
[root@centos011 ~]#

查看除了pod的资源 kubectl get rc,service

[root@centos011 ~]# kubectl get rc,service
NAME                  DESIRED   CURRENT   READY     AGE
rc/nginx-controller   2         2         0         22h   两个rc服务

NAME             CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
svc/kubernetes   192.168.142.1   <none>        443/TCP   9d  一个Service服务

[root@centos011 ~]# kubectl delete rc –all

删除service 命令
[root@centos011 ~]# kubectl get service
NAME         CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes   192.168.142.1   <none>        443/TCP   32s
[root@centos011 ~]# kubectl delete services kubernetes
service "kubernetes" deleted
[root@centos011 ~]#
[root@centos011 ~]#
[root@centos011 ~]# kubectl get service
No resources found.
[root@centos011 ~]#

官方命令
[root@centos011 ~]# kubectl get service –all
Error: unknown flag: –all

Examples:
  # List all pods in ps output format.
  kubectl get pods
 
  # List all pods in ps output format with more information (such as node name).
  kubectl get pods -o wide
 
  # List a single replication controller with specified NAME in ps output format.
  kubectl get replicationcontroller web
 
  # List a single pod in JSON output format.
  kubectl get -o json pod web-pod-13je7
 
  # List a pod identified by type and name specified in "pod.yaml" in JSON output format.
  kubectl get -f pod.yaml -o json
 
  # Return only the phase value of the specified pod.
  kubectl get -o template pod/web-pod-13je7 –template={{.status.phase}}
 
  # List all replication controllers and services together in ps output format.
  kubectl get rc,services
 
  # List one or more resources by their type and names.
  kubectl get rc/web service/frontend pods/web-pod-13je7

一看必会系列:kubernetes排错及高级配置1

  kubectl get pod –all-namespaces
  kubectl get service –namespace=kube-system
  kubectl get pods –namespace=kube-system
  kubectl describe pod nginx-controller-mbs7l
——————-以下是排错及高级应用—————————
  kubectl get pod –all-namespaces
 
[root@master ~]# kubectl get pod –all-namespaces
NAMESPACE     NAME                                           READY     STATUS             RESTARTS   AGE
default       nginx-pod                                      1/1       Running            0          10h
kube-system   kubernetes-dashboard-latest-3308158392-8wj3w   0/1       ImagePullBackOff   0          10h

 
  kubectl get service –namespace=kube-system

[root@master ~]#   kubectl get service –namespace=kube-system
NAME                   CLUSTER-IP        EXTERNAL-IP   PORT(S)   AGE
kubernetes-dashboard   192.168.142.222   <none>        80/TCP    10h
 
  kubectl get pods –namespace=kube-system
 
[root@master ~]#   kubectl get pods –namespace=kube-system
NAME                                           READY     STATUS             RESTARTS   AGE
kubernetes-dashboard-latest-3308158392-8wj3w   0/1       ImagePullBackOff   0          10h
 
  kubectl get service –namespace=kube-system
 
[root@master ~]#   kubectl get service –namespace=kube-system
NAME                   CLUSTER-IP        EXTERNAL-IP   PORT(S)   AGE
kubernetes-dashboard   192.168.142.222   <none>        80/TCP    10h
 
  kubectl get pods –namespace=kube-system
  kubectl get  -f kubernetes-dashboard.yaml
 
 
 

   
—————–部署nginx测试——————-
nginx-pod.yaml
   
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
  name: nginx-pod
spec:
containers:
– name: nginx
   image: nginx
   ports:
   – containerPort: 80

   
   
http://blog.csdn.net/u013760355/article/details/68061976   
[root@master ~]# kubectl create -f /opt/dockerconfig/nginx-pod.yaml
Error from server (ServerTimeout): error when creating "/opt/dockerconfig/nginx-pod.yaml": No API token found for service account "default", retry after the token is automatically created and added to the service account

报错是验证产生的

[root@master ~]# vim /etc/kubernetes/apiserver

去掉相应配置
#KUBE_ADMISSION_CONTROL="–admission-control=NamespaceLifecycle,NamespaceExists,LimitRanger,SecurityContextDeny,ServiceAccount,ResourceQuota"
KUBE_ADMISSION_CONTROL="–admission-control=NamespaceLifecycle,NamespaceExists,LimitRanger,ResourceQuota"

[root@master ~]# systemctl restart kube-apiserver
[root@master ~]#
解决

[root@master ~]# kubectl create -f /opt/dockerconfig/nginx-pod.yaml
pod "nginx-pod" created
[root@master ~]#

但是一直卡着
[root@master ~]# kubectl get pods
NAME        READY     STATUS              RESTARTS   AGE
nginx-pod   0/1       ContainerCreating   0          12m
[root@master ~]# kubectl get service
NAME         CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes   192.168.142.1   <none>        443/TCP   1h
[root@master ~]#
主要是通过“kubectl describe pod PodName”指令查看pod发生的事件,从事件列表中可以查找到错误信息。
查状态
[root@master ~]# kubectl get pods
NAME        READY     STATUS              RESTARTS   AGE
nginx-pod   0/1       ContainerCreating   0          12m
[root@master ~]# kubectl get service
NAME         CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes   192.168.142.1   <none>        443/TCP   1h
[root@master ~]# kubectl describe pod gninx
Error from server (NotFound): pods "gninx" not found
[root@master ~]# kubectl describe pod nginx
Name:        nginx-pod
Namespace:    default
Node:        192.168.142.131/192.168.142.131
Start Time:    Thu, 18 Jan 2018 08:39:59 -0500
Labels:        name=nginx-pod
Status:        Pending
IP:       
Controllers:    <none>
Containers:
  nginx:
    Container ID:       
    Image:            nginx
    Image ID:           
    Port:            80/TCP
    State:            Waiting
      Reason:            ContainerCreating
    Ready:            False
    Restart Count:        0
    Volume Mounts:        <none>
    Environment Variables:    <none>
Conditions:
  Type        Status
  Initialized     True
  Ready     False
  PodScheduled     True
No volumes.
QoS Class:    BestEffort
Tolerations:    <none>
Events:
  FirstSeen    LastSeen    Count    From                SubObjectPath Type        Reason        Message
  ———    ——–    —–    —-                ————- ——–    ——        ——-
  15m        15m        1    {default-scheduler }                  Normal        Scheduled    Successfully assigned nginx-pod to 192.168.142.131
  15m        4m        7    {kubelet 192.168.142.131}              Warning        FailedSync    Error syncing pod, skipping: failed to "StartContainer" for "POD" with ErrImagePull: "image pull failed for registry.access.redhat.com/rhel7/pod-infrastructure:latest, this may be because there are no credentials on this request.  details: (open /etc/docker/certs.d/registry.access.redhat.com/redhat-ca.crt: no such file or directory)"

  14m    12s    64    {kubelet 192.168.142.131}        Warning    FailedSync    Error syncing pod, skipping: failed to "StartContainer" for "POD" with ImagePullBackOff: "Back-off pulling image \"registry.access.redhat.com/rhel7/pod-infrastructure:latest\""

哈哈,你懂的
Error syncing pod, skipping: failed to "StartContainer" for "POD" with ImagePullBackOff: "Back-off pulling image \"registry.access.redhat.com/rhel7/pod-infrastructure:latest\""
[root@master ~]#

手动下载
[root@master ~]# docker pull registry.access.redhat.com/rhel7/pod-infrastructure:latest
Trying to pull repository registry.access.redhat.com/rhel7/pod-infrastructure …
open /etc/docker/certs.d/registry.access.redhat.com/redhat-ca.crt: no such file or directory
[root@master ~]#

———解决方法1 已失效,现版不知为毛这两包装了没用
[root@master ~]# yum install *rhsm* -y         —-安装

Installed:
  python-rhsm.x86_64 0:1.19.10-1.el7_4                                       python-rhsm-certificates.x86_64 0:1.19.10-1.el7_4                                     

Dependency Installed:
  python-dateutil.noarch 0:1.5-7.el7                                                                                                                                

Complete!

———-解决方法2

[root@master ~]# docker pull registry.access.redhat.com/rhel7/pod-infrastructure:latest
Trying to pull repository registry.access.redhat.com/rhel7/pod-infrastructure …
latest: Pulling from registry.access.redhat.com/rhel7/pod-infrastructure

26e5ed6899db: Pulling fs layer
66dbe984a319: Pulling fs layer
^C38e7863e08: Pulling fs layer

———前两个方案已失效用第三种
wget http://mirror.centos.org/centos/7/os/x86_64/Packages/python-rhsm-certificates-1.19.10-1.el7_4.x86_64.rpm
rpm -ivh  python-rhsm-certificates-1.19.10-1.el7_4.x86_64.rpm
[root@k8s_master ~]# rpm -ivh python-rhsm-certificates-1.19.10-1.el7_4.x86_64.rpm
Preparing…                          ################################# [100%]
Updating / installing…
   1:python-rhsm-certificates-1.19.10-################################# [100%]
[root@k8s_master ~]# !ll
ll /etc/rhsm/ca/
total 8
-rw-r–r– 1 root root 7732 Oct 20  2017 redhat-uep.pem   ——就是这个文件

 

等10个小时就好了
[root@master ~]#   kubectl get pods
NAME        READY     STATUS    RESTARTS   AGE
nginx-pod   1/1       Running   0          11h

 

新建nginx-service.
[root@master dockerconfig]# kubectl create -f nginx-service.yaml
service "nginx-service" created
[root@master dockerconfig]# kubectl get -f nginx-service.yaml
NAME            CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
nginx-service   192.168.142.65   <nodes>       80:30001/TCP   8s
[root@master dockerconfig]#

访问 node1的 30001端口测试成功

———–
  在master节点上启动

systemctl enable flanneld.service
systemctl start flanneld.service
service docker restart
systemctl restart kube-apiserver.service
systemctl restart kube-controller-manager.service
systemctl restart kube-scheduler.service

for SERVICES in etcd kube-apiserver kube-controller-manager kube-scheduler   kube-proxy  kubelet docker flanneld   ;
do systemctl restart   $SERVICES; systemctl enable $SERVICES; systemctl status $SERVICES; done;

在各个Nodes上启动

systemctl enable flanneld.service
systemctl start flanneld.service
service docker restart
systemctl restart kubelet.service
systemctl restart kube-proxy.service

node启动

for SERVICES in kube-proxy kubelet docker flanneld; do
        systemctl restart $SERVICES
        systemctl enable $SERVICES
        systemctl status $SERVICES
    done;

一看必会系列:docker tomcat容器测试

No Comments 容器技术

仓库服务器操作

拉的国内源,原厂源太慢
docker search registry.docker-cn.com/library/tomcat
docker pull registry.docker-cn.com/library/tomcat
docker images

打包推到本地

docker tag registry.docker-cn.com/library/tomcat 192.168.142.130:5000/tomcat:v1
docker images
docker images |grep 5000
docker ps
docker push 192.168.142.130:5000/tomcat:v1
docker images

应用服务器操作

docker pull 192.168.142.130:5000/tomcat:v1
vim /opt/dockerfiles/Dockerfile
FROM 192.168.142.130:5000/tomcat:v1
copy login.jsp /usr/local/tomcat/webapps/

docker build -t jefftomcat:v2 .

docker run -itd -p 808:8080  jefftomcat:v2 /bin/bash

更新源
建议先更新国内源  方式http://www.jdccie.com/?p=3821
apt-get update && apt-get install vim -y

apt-get install vim
cat /proc/version
uname
uname -a
cat /proc/version
sb_reease -a
rb_release
cat /etc/issue  发现版本是debian
apt-get install net-tools
netstat -ntlp    发现端口没起动

cd bin/
./startup.sh    国内源和原厂不一样,不是自己启动,需要手动运行
netstat -ntlp
java -version
root@81128bff7253:/usr/local/tomcat/webapps# !net
netstat -ntlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name   
tcp6       0      0 127.0.0.1:8005          :::*                    LISTEN      438/java           
tcp6       0      0 :::8009                 :::*                    LISTEN      438/java           
tcp6       0      0 :::8080                 :::*                    LISTEN      438/java

测试文件放这里
root@81128bff7253:/usr/local/tomcat/webapps/ROOT/login.jsp

login.jsp内容如下
<%@ page import="java.sql.*" language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登录界面</title>
</head>
<body>
    <center>
        <h1 style="color:red">登录</h1>
            <form id="indexform" name="indexForm" action="logincheck.jsp" method="post">
                <table border="0">
                    <tr>
                        <td>账号:</td>
                        <td><input type="text" name="username"></td>
                    </tr>
                    <tr>
                        <td>密码:</td>
                        <td><input type="password" name="password">
                        </td>
                    </tr>
                </table>
            <br>
                <input type="submit" value="登录" style="color:#BC8F8F">
            </form>
            <form action="zhuce.jsp">
                <input type="submit" value="注册" style="color:#BC8F8F">
            </form>
    </center>
</body>
</html>

docker 容器替换其它源的最佳方式

No Comments 容器技术

启动
docker run -itd -p 808:8080  jefftomcat:v2 /bin/bash
看进程
docker ps
将apt/source.list复制到本地服务器

docker cp 容器ID:/容器目录  地本目录

docker cp 81128bff7253:/etc/apt/ tmp
 
编辑source.list文件
docker cp sources.list 81128bff7253:/etc/apt/
docker attach 81128bff7253
vim sources.list
复制回去
docker cp sources.list 81128bff7253:/etc/apt/
直接进去更新

docker attach 容器ID
docker attach 81128bff7253
  root@81128bff7253:/usr/local/tomcat/bin#  apt-get update

内容如下
deb http://mirrors.aliyun.com/debian/ stretch main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ stretch main non-free contrib
deb http://mirrors.aliyun.com/debian-security stretch/updates main
deb-src http://mirrors.aliyun.com/debian-security stretch/updates main
deb http://mirrors.aliyun.com/debian/ stretch-updates main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ stretch-updates main non-free contrib
deb http://mirrors.aliyun.com/debian/ stretch-backports main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ stretch-backports main non-free contrib

docker Error response from daemon 解决

No Comments 容器技术

[root@localhost ~]# docker search ubantu

Error response from daemon: Get https://index.docker.io/v1/search?q=ubantu&n=25: x509: certificate has expired or is not yet valid

 

解决

vim /etc/chrony.conf   更新ntp服务器
systemctl restart chronyd
date
timedatectl set-timezone Asia/Shanghai  设置时区
date
chronyc sources -v   查看同步

以下为正常。即可使用docker search
[root@centos010 ~]# chronyc sources -v
210 Number of sources = 1

  .– Source mode  ‘^’ = server, ‘=’ = peer, ‘#’ = local clock.
/ .- Source state ‘*’ = current synced, ‘+’ = combined , ‘-‘ = not combined,
| /   ‘?’ = unreachable, ‘x’ = time may be in error, ‘~’ = time too variable.
||                                                 .- xxxx [ yyyy ] +/- zzzz
||      Reachability register (octal) -.           |  xxxx = adjusted offset,
||      Log2(Polling interval) –.      |          |  yyyy = measured offset,
||                                \     |          |  zzzz = estimated error.
||                                 |    |           \
MS Name/IP address         Stratum Poll Reach LastRx Last sample              
===============================================================================
^* 118.24.4.66                   2   6   377    62   -821us[-2454us] +/-   66ms
[root@centos010 ~]#

一看必会系列:docker mysql 主从集群测试

No Comments 容器技术

 

仓库操作
docker pull mysql:5.6
docker images
docker tag docker.io/mysql 192.168.142.130:5000/mysql56:v2
docker tag 97fdbdd65c6a 192.168.142.130:5000/mysql56:v2
docker images
docker push 192.168.142.130:5000/mysql56:v2

主从服务器操作

docker run   –restart=always -p  3356:3306 –name masterdb -v  /db/mysqlCluster/master:/var/lib/mysql  -e  MYSQL_ROOT_PASSWORD=123456   -d  192.168.142.130:5000/mysql56:v2

docker run   –restart=always -p  3356:3306 –name slavedb -v  /db/mysqlCluster/master:/var/lib/mysql  -e  MYSQL_ROOT_PASSWORD=123456   -d  192.168.142.130:5000/mysql56:v2

进主服务器
docker exec -it masterdb /bin/bash
进从服务器
docker exec -it slavedb /bin/bash

apt-get update && apt-get install vim -y

进入容器修改配置文件
[root@centos010 ~]# docker exec -it masterdb /bin/bash
root@9838a377e3e2:/# vim /etc/mysql/mysql.conf.d/mysqld.cnf

主服务器配置
server-id = 1
log_bin = mysql-bin
lower_case_table_names=1

从服务器配置
server-id = 2
log_bin = mysql-bin
lower_case_table_names=1

root@9838a377e3e2:/# mysql -u root -p      
Enter password:

主从服务器配置,实际这个权限给只读就行
GRANT REPLICATION SLAVE ON *.* TO ‘re’@’%’ IDENTIFIED BY ‘123456’;
flush privileges;

从服务器
注意端口
CHANGE MASTER TO MASTER_HOST=’192.168.142.130′,MASTER_USER=’re’, MASTER_PASSWORD=’123456′,MASTER_LOG_FILE=’mysql-bin.000001′, MASTER_LOG_POS=387, master_port=3356;
flush privileges;
start slave;

从服务器查看
mysql> show slave STATUS \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.142.130
                  Master_User: re
                  Master_Port: 3356
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 387
               Relay_Log_File: mysqld-relay-bin.000002
                Relay_Log_Pos: 283
        Relay_Master_Log_File: mysql-bin.000001
             Slave_IO_Running: Yes   —成功
            Slave_SQL_Running: Yes

从服务器建立普通帐号测试只读
GRANT select ON *.* TO ‘user01’@’%’ IDENTIFIED BY’123456′ WITH GRANT OPTION;

一小时Docker教程

No Comments 容器技术

 

Docker基础

这篇基础文章是方便用户在使用cSphere平台之前,了解docker基础知识。

针对已经有一定的Linux基础知识的用户。

Docker是什么

Docker是一个改进的容器技术。具体的“改进”体现在,Docker为容器引入了镜像,使得容器可以从预先定义好的模版(images)创建出来,并且这个模版还是分层的。

Docker经常被提起的特点:

轻量,体现在内存占用小,高密度
快速,毫秒启动
隔离,沙盒技术更像虚拟机
Docker技术的基础:

namespace,容器隔离的基础,保证A容器看不到B容器. 6个名空间:User,Mnt,Network,UTS,IPC,Pid
cgroups,容器资源统计和隔离。主要用到的cgroups子系统:cpu,blkio,device,freezer,memory
unionfs,典型:aufs/overlayfs,分层镜像实现的基础
Docker组件:

docker Client客户端————>向docker服务器进程发起请求,如:创建、停止、销毁容器等操作
docker Server服务器进程—–>处理所有docker的请求,管理所有容器
docker Registry镜像仓库——>镜像存放的中央仓库,可看作是存放二进制的scm
Docker安装

Docker的安装非常简单,支持目前所有主流操作系统,从Mac到Windows到各种Linux发行版
具体参考: docker安装

Docker常见命令

容器相关操作

docker create # 创建一个容器但是不启动它
docker run # 创建并启动一个容器
docker stop # 停止容器运行,发送信号SIGTERM
docker start # 启动一个停止状态的容器
docker restart # 重启一个容器
docker rm # 删除一个容器
docker kill # 发送信号给容器,默认SIGKILL
docker attach # 连接(进入)到一个正在运行的容器
docker wait # 阻塞到一个容器,直到容器停止运行
获取容器相关信息

docker ps # 显示状态为运行(Up)的容器
docker ps -a # 显示所有容器,包括运行中(Up)的和退出的(Exited)
docker inspect # 深入容器内部获取容器所有信息
docker logs # 查看容器的日志(stdout/stderr)
docker events # 得到docker服务器的实时的事件
docker port # 显示容器的端口映射
docker top # 显示容器的进程信息
docker diff # 显示容器文件系统的前后变化
导出容器

docker cp # 从容器里向外拷贝文件或目录
docker export # 将容器整个文件系统导出为一个tar包,不带layers、tag等信息
执行

docker exec # 在容器里执行一个命令,可以执行bash进入交互式
镜像操作

docker images # 显示本地所有的镜像列表
docker import # 从一个tar包创建一个镜像,往往和export结合使用
docker build # 使用Dockerfile创建镜像(推荐)
docker commit # 从容器创建镜像
docker rmi # 删除一个镜像
docker load # 从一个tar包创建一个镜像,和save配合使用
docker save # 将一个镜像保存为一个tar包,带layers和tag信息
docker history # 显示生成一个镜像的历史命令
docker tag # 为镜像起一个别名
镜像仓库(registry)操作

docker login # 登录到一个registry
docker search # 从registry仓库搜索镜像
docker pull # 从仓库下载镜像到本地
docker push # 将一个镜像push到registry仓库中
获取Container IP地址(Container状态必须是Up)

docker inspect id | grep IPAddress | cut -d ‘"’ -f 4
获取端口映射

docker inspect -f ‘{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}’ id
获取环境变量

docker exec container_id env
杀掉所有正在运行的容器

docker kill $(docker ps -q)
删除老的(一周前创建)容器

docker ps -a | grep ‘weeks ago’ | awk ‘{print $1}’ | xargs docker rm
删除已经停止的容器

docker rm `docker ps -a -q`
删除所有镜像,小心

docker rmi $(docker images -q)
Dockerfile

Dockerfile是docker构建镜像的基础,也是docker区别于其他容器的重要特征,正是有了Dockerfile,docker的自动化和可移植性才成为可能。

不论是开发还是运维,学会编写Dockerfile几乎是必备的,这有助于你理解整个容器的运行。

FROM , 从一个基础镜像构建新的镜像

FROM ubuntu
MAINTAINER , 维护者信息

MAINTAINER William <wlj@nicescale.com>
ENV , 设置环境变量

ENV TEST 1
RUN , 非交互式运行shell命令

RUN apt-get -y update
RUN apt-get -y install nginx
ADD , 将外部文件拷贝到镜像里,src可以为url

ADD http://nicescale.com/  /data/nicescale.tgz
WORKDIR /path/to/workdir, 设置工作目录

WORKDIR /var/www
USER , 设置用户ID

USER nginx
VULUME <#dir>, 设置volume

VOLUME [‘/data’]
EXPOSE , 暴露哪些端口

EXPOSE 80 443
ENTRYPOINT [‘executable’, ‘param1’,’param2’]执行命令

ENTRYPOINT ["/usr/sbin/nginx"]
CMD [“param1”,”param2”]

CMD ["start"]
docker创建、启动container时执行的命令,如果设置了ENTRYPOINT,则CMD将作为参数

Dockerfile最佳实践

尽量将一些常用不变的指令放到前面
CMD和ENTRYPOINT尽量使用json数组方式
通过Dockerfile构建image

docker build csphere/nginx:1.7 .
镜像仓库Registry

镜像从Dockerfile build生成后,需要将镜像推送(push)到镜像仓库。企业内部都需要构建一个私有docker registry,这个registry可以看作二进制的scm,CI/CD也需要围绕registry进行。

部署registry

mkdir /registry
docker run  -p 80:5000  -e STORAGE_PATH=/registry  -v /registry:/registry  registry:2.0
推送镜像保存到仓库

假设192.168.1.2是registry仓库的地址:

docker tag  csphere/nginx:1.7 192.168.1.2/csphere/nginx:1.7
docker push 192.168.1.2/csphere/nginx:1.7
几个简单小例子

容器操作

1.创建并拉取busybox

# docker run -it –name con01 busybox:latest
/ # ip addr    #容器里执行
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
   valid_lft forever preferred_lft forever
Segmentation fault (core dumped)
/ # ping www.csphere.cn
PING www.csphere.cn (117.121.26.243): 56 data bytes
64 bytes from 117.121.26.243: seq=0 ttl=48 time=3.139 ms
64 bytes from 117.121.26.243: seq=1 ttl=48 time=3.027 ms
^C
— www.csphere.cn ping statistics —
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 3.027/3.083/3.139 ms
exit    #退出容器
2.创建测试容器

docker run -d –name con03 csphere/test:0.1
efc9bda4a2ff2f479b18e0fc4698e42c47c9583a24c93f5ce6b28a828a172709
3.登陆到con03中

# docker exec -it con03 /bin/bash
[root@efc9bda4a2ff /]# exit
4.停止con03

# docker stop con03
con03
5.开启con03

# docker start con03
con03
6.删除con03

# docker ps -a
CONTAINER ID        IMAGE                    COMMAND                CREATED             STATUS                      PORTS                                             NAMES
efc9bda4a2ff        csphere/test:0.1         "/usr/local/bin/run    4 minutes ago       Up 17 seconds                                                                 con03              
99aa6ee25adc        busybox:latest           "/bin/sh"              14 minutes ago      Exited (0) 12 minutes ago                                                     con02              
831c93de9b9f        busybox:latest           "/bin/sh"              2 hours ago         Up 27 minutes                                                                 con01
# docker rm con02     #容器停止的状态
# docker rm -f con03  #容器开启的状态
镜像操作

1.从docker hub官方镜像仓库拉取镜像

# docker pull busybox:latest
atest: Pulling from busybox
cf2616975b4a: Pull complete
6ce2e90b0bc7: Pull complete
8c2e06607696: Already exists
busybox:latest: The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security.
Digest: sha256:38a203e1986cf79639cfb9b2e1d6e773de84002feea2d4eb006b52004ee8502d
Status: Downloaded newer image for busybox:latest
2.从本地上传镜像到镜像仓库

docker push 192.168.1.2/csphere/nginx:1.7
3.查找镜像仓库的某个镜像

# docker search centos/nginx
NAME                                     DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
johnnyzheng/centos-nginx-php-wordpress                                                   1                    [OK]
sergeyzh/centos6-nginx                                                                   1                    [OK]
hzhang/centos-nginx                                                                      1                    [OK]
4.查看本地镜像列表

# docker images
TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
docker.io/csphere/csphere   0.10.3              604c03bf0c9e        3 days ago          62.72 MB
docker.io/csphere/csphere   latest              604c03bf0c9e        3 days ago          62.72 MB
csphere/csphere             0.10.3              604c03bf0c9e        3 days ago          62.72 MB
registry                    2.0                 2971b6ce766c        7 days ago          548.1 MB
busybox                     latest              8c2e06607696        3 weeks ago         2.43 MB
5.删除镜像

docker rmi busybox:latest        #没有容器使用此镜像创建,如果有容器在使用此镜像会报错:Error response from daemon: Conflict, cannot delete 8c2e06607696 because the running container 831c93de9b9f is using it, stop it and use -f to force
FATA[0000] Error: failed to remove one or more images
docker rmi -f busybox:latest     #容器使用此镜像创建,此容器状态为Exited
6.查看构建镜像所用过的命令

# docker history busybox:latest
IMAGE               CREATED             CREATED BY                                      SIZE
8c2e06607696        3 weeks ago         /bin/sh -c #(nop) CMD ["/bin/sh"]               0 B
6ce2e90b0bc7        3 weeks ago         /bin/sh -c #(nop) ADD file:8cf517d90fe79547c4   2.43 MB
cf2616975b4a        3 weeks ago         /bin/sh -c #(nop) MAINTAINER Jér?me Petazzo     0 B
一小时Docker教程

一小时Docker教程