以下是在Ubuntu虚拟机上实践容器化应用的步骤,涵盖Docker和Kubernetes两种主流方案:
sudo apt update
sudo apt install docker.io
sudo systemctl start docker && sudo systemctl enable docker
sudo docker run hello-world
Dockerfile:FROM python:3.9-slim
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
EXPOSE 5000
CMD ["python", "app.py"]
docker build -t my-app:1.0 .
docker run -d -p 5000:5000 --name my-app my-app:1.0
docker-compose.yml:version: '3'
services:
web:
image: my-app:1.0
ports:
- "5000:5000"
redis:
image: redis:latest
启动服务:docker-compose up -d
sudo apt update
sudo apt install -y docker.io kubelet kubeadm kubectl
sudo systemctl enable docker && sudo systemctl start docker
/etc/docker/daemon.json:{
"exec-opts": ["native.cgroupdriver=systemd"]
}
sudo systemctl restart docker
sudo kubeadm init --pod-network-cidr=10.244.0.0/16
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
kubeadm join命令。deployment.yaml:apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
image: my-app:1.0
ports:
- containerPort: 5000
部署应用:kubectl apply -f deployment.yaml
service.yaml:apiVersion: v1
kind: Service
metadata:
name: my-app-service
spec:
selector:
app: my-app
ports:
- protocol: TCP
port: 80
targetPort: 5000
type: LoadBalancer
应用服务:kubectl apply -f service.yaml
kubectl get pods
kubectl get services
kubectl delete -f deployment.yaml
kubectl delete -f service.yaml
kubectl top nodes监控节点资源使用情况。volumes将容器数据挂载到宿主机或云存储,避免重启后数据丢失。通过以上步骤,可在Ubuntu虚拟机上完成从单容器到集群化的应用部署,满足开发、测试或轻量级生产环境需求。