docker搭建nginx

使用docker来搭建nginx

1. 使用docker run 的方式创建

  1. 创建配置文件目录

    1
    2
    3
    mkdir -p /opt/docker-data/nginx/conf/conf.d
    mkdir -p /opt/docker-data/nginx/html
    mkdir -p /opt/docker-data/nginx/logs
  2. 拉取镜像

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    [root@zmr-service opt]# docker pull nginx:1.24.0

    1.24.0: Pulling from library/nginx
    26c5c85e47da: Pull complete
    7e385399569d: Pull complete
    38454a0c2b53: Pull complete
    70163c4a088e: Pull complete
    283e8681fce8: Pull complete
    8459642afffc: Pull complete
    Digest: sha256:22cb51c7e9e05724dd1c46789e15cdb78617d1904c7c78a2829c8550c6b46e40
    Status: Downloaded newer image for nginx:1.24.0
    docker.io/library/nginx:1.24.0

  3. 直接起一个容器

    先起一个nginx容器将里面的配置复制出来,然后再起。否则的话由于没有活动的服务,docker在启动后就会直接退出。

    1
    docker run --name my-nginx  -d nginx:1.24.0
  4. 将容器中的配置文件复制一份到本地目录中

    1
    2
    3
    4
    5
    6
    7
    8
    # 先确认容器的id
    [root@zmr-service opt]# docker ps|grep nginx
    ea7d93a83e89 nginx:1.24.0 "/docker-entrypoint.…" 15 seconds ago Up 15 seconds 80/tcp my-nginx

    # 复制需要的文件
    docker cp ea7d93a83e89:/etc/nginx/nginx.conf /opt/docker-data/nginx/conf/nginx.conf
    docker cp ea7d93a83e89:/etc/nginx/conf.d /opt/docker-data/nginx/conf
    docker cp ea7d93a83e89:/usr/share/nginx/html /opt/docker-data/nginx
  5. 拷贝完之后就停止并删除容器

    1
    2
    docker stop my-nginx
    docker rm my-nginx
  6. 创建需要的nginx容器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    # 暴露自己需要的端口
    docker run \
    -p 80:80 \
    --name nginx_web \
    --restart=always \
    -e LC_ALL="en_US.UTF-8" \
    -e TZ="Asia/Shanghai" \
    -v /opt/docker-data/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
    -v /opt/docker-data/nginx/conf/conf.d:/etc/nginx/conf.d \
    -v /opt/docker-data/nginx/html:/usr/share/nginx/html \
    -v /opt/docker-data/nginx/logs:/var/log/nginx \
    -d \
    nginx:1.24.0

    2. 使用docker-compose的方式创建

    docker-compose.yml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    version: "3"

    services:
    nginx:
    container_name: nginx
    image: nginx:1.24.0
    restart: always
    ports:
    - 80:80
    volumes:
    - /opt/docker-data/nginx/conf/nginx.conf:/etc/nginx/nginx.conf
    - /opt/docker-data/nginx/www:/home/www
    - /opt/docker-data/nginx/logs:/var/log/nginx
    - /opt/docker-data/nginx/conf/conf.d:/etc/nginx/conf.d
    - /opt/docker-data/nginx/html:/usr/share/nginx/html