Docker 實戰—使用 Dockerfile 構建鏡像

GitHub Page:http://blog.cloudli.top/posts/Docker實戰-使用-Dockerfile-構建鏡像/html

Dockerfile 指令詳解請訪問:http://www.javashuo.com/article/p-ekfnhhto-dx.htmllinux

使用 Alpine Linux 做爲基礎鏡像

Alpine 是一個很是輕量的 Linux 鏡像,他只有大約 5MB 的大小,基於它構建鏡像,能夠大大減小鏡像的體積。nginx

Alpine 的 Docker Hub 頁面:https://hub.docker.com/_/alpinedocker

docker pull alpine

Alpine 使用 apk 命令來安裝軟件包,支持的軟件包列表能夠在官網查看:https://pkgs.alpinelinux.org/packagesshell

這裏以安裝 Nginx 爲例,學習鏡像的構建。另外 Nginx 自己有官方鏡像,pull 便可。緩存

構建 Nginx 鏡像

編寫 Dockerfile

FROM alpine

RUN apk update \
    # 安裝 nginx
    apk add --no-cache nginx \
    mkdir /run/nginx && \
    # 清除緩存
    rm -rf /tmp/* /var/cache/apk/*
    
# 添加容器啓動命令,啓動 nginx,之前臺方式運行
CMD [ "nginx", "-g", "daemon off;" ]

這裏有一個坑點,必須建立 /run/nginx 目錄,否則會報錯。post

構建鏡像

使用 docker build 命令構建:學習

docker build -t nginx-alpine .

在 Dockerfile 目錄下執行以上命令便可構建鏡像。-t 參數指定了鏡像名稱爲 nginx-alpine,最後的 . 表示構建上下文(. 表示當前目錄).ui

在使用 COPY 指令複製文件時,指令中的源路徑是相對於構建上下文的(若是指定上下文爲 /home,那麼至關於全部的源路徑前面都加上了 /home/)。code

若是你的 Dockerfile 文件名不是 「Dockerfile」,可使用 -f 參數指定。

千萬不要將 Dockerfile 放在根目錄下構建,假如你將 Dockerfile 放在一個存放大量視頻目錄下,而且構建上下文爲當前目錄,那麼鏡像將會很是大(視頻都被打包進去了)。最佳作法是將 Dockerfile 和須要用到的文件放在一個單獨的目錄下。

運行容器

使用構建的鏡像運行容器:

docker run --name my-nginx -p 80:80 -d nginx-apline
  • --name 指定容器的名稱,能夠省略(後續只能經過容器 id 來操做);
  • -p 映射端口,宿主端口 -> 容器端口;
  • -d 後臺運行。

運行後訪問 http://localhost/,會出現一個 nginx 的 404 頁面,說明已經運行成功了,由於這裏安裝的 Nginx 並無默認頁面,/etc/nginx/conf.d/default.conf 中的內容:

# This is a default site configuration which will simply return 404, preventing
# chance access to any other virtualhost.

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # Everything is a 404
        location / {
                return 404;
        }
}

使用構建的 Nginx 鏡像運行一個靜態頁面

在一個空目錄下建立 Nginx 配置文件:

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www;
        
        location / {
                index index.html;
        }
}

編寫一個靜態頁面:

<!DOCTYPE html>
<html>
    <head>
        <title>Index</title>
    </head>
    <body>
        <h1>Hello, Docker!</h1>
    </body>
</html>

使用以前構建的鏡像構建一個新的鏡像:

FROM nginx-alpine
# 拷貝配置文件,覆蓋默認的
COPY default.conf /etc/nginx/conf.d/
# 拷貝靜態頁面
COPY index.html /var/www

構建鏡像、運行容器:

docker build -t site .
docker run --name my-site -p 80:80 -d site

如今訪問 http://localhost/,就能夠看到 Hello, Docker!

相關文章
相關標籤/搜索