Docker 语法快速预览

安装

基本概念

  • 镜像: 一个操作系统
  • 容器: 一个操作系统的实例
  • 仓库: 存储镜像的地方

镜像使用

查找镜像
docker search
获取镜像
docker pull ubuntu:18.04
列出本地镜像
docker image ls
本地占用空间
docker system df
删除镜像
docker image rm [镜像名|镜像Id]
docker image rm ubuntu

操作容器

启动

  • 运行之后终止docker run ubuntu:18.04 /bin/echo 'Hello world'
  • 进入终端docker run -t -i ubuntu:18.04 /bin/bash
  • 后台运行
    docker run -d ubuntu:18.04 /bin/sh -c "while true; do echo hello world; sleep 1; done"
    docker run -dit ubuntu
    • 后台运行的容器 docker container ls
    • 重新进入 docker exec -it [container id] bash
    • 终止后的容器 docker container ls -a
    • 启动终止后的容器docker container start [container id]
    • 终止容器docker container stop [container id]

退出
在容器终端 exit

导出
docker container ls -a
docker export [container id] > ubuntu.tar

导入

$ cat ubuntu.tar | docker import - test/ubuntu:1.0
$ docker image ls

删除

  • docker container prune 删除全部终止的容器
  • docker container rm [container id] 删除终止后的容器
  • docker container rm -f [contaienr id] 删除正在运行的容器

构建镜像

  1. 编写Dockerfile 2. 运行命令
$ mkdir docker;cd docer; touch t/1.txt;vi Dockerfile

// Dockerfile
#以本地 ubuntu 为基础
FROM ubuntu
#定义变量
ENV VERSION 7.2

#复制本地文件到镜像里
COPY t/* /root/
#在镜像里运行shell命令
RUN mkdir /root/test \
 && mkdir /root/test2
 && touch "$VERSION"
$ docker build -t test:1.0 .
$ docker image ls

访问容器服务

将本机5000端口映射到容器5000
$ docker run -d -p 5000:5000 training/webapp python app.py

案例

构建node服务器

// 开发环境 ubuntu
// ubuntu:18.04 不存在会自动下载
$ docker run -it ubuntu:18.04 /bin/bash
// 进入了ubuntu:18.04 终端
$ apt-get update
$ apt-get install curl; apt-get install vim
// node 安装 https://github.com/nodejs/help/wiki/Installation#how-to-install-nodejs-via-binary-archive-on-linux
$ cd /root; mkdir server; cd server;  npm init -y; npm i koa; vi sever.js;

// server.js---------
const Koa = require('koa')
const app = new Koa()
app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin','*')
    await next();
}); 
app.use(async (ctx)=>{
    ctx.response.body = "<h1>hello</h1>"
})
app.listen(3000);
console.log('app started at port 3000...');
// ----

$ exit
$ docker run -d -p 3000:3000 ubuntu:18.04 /bin/sh -c ". ~/.profile; node /root/server/server.js"
$ docker container logs [container id]
// 返回<h1>hello</h1> 成功了
$ curl 127.0.0.1:3000
$ docker export [container id] > node.tar
// 迁移到其他服务器时直接导入
$ cat node.tar | docker import - node:1.0
$ docker image ls
// 启动
$ docker run -d -p 3000:3000 node:1.0 /bin/sh -c ". ~/.profile; node /root/server/server.js"

Docker 入门

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容