docker 安装 nginx

一、环境

  1. 系统版本:CentOS 7.3,内核:x86_64  
uname -r

[root@localhost ~]# uname -r    
3.10.0-514.el7.x86_64

二、nginx安装

  1.先用docker拉去一份nginx的镜像

注意:这里下载的版本与后续docker-compose.yml中版本需一致)

  

#拉取命令
docker pull nginx

2.运行nginx镜像

docker run --name nginx -d -p 5082:5082 nginx
查看nginx容器是否运行成功
docker ps -a

在容器外部使用复制命令

# 冒号前面的地址是要复制的内容的地址,冒号后面是你要复制之后放的地方(此处需要先创建该目录)
docker container cp webserver:/etc/nginx/conf.d/default.conf  /home/application/docker_nginx/conf.d/
#容器内该目录下文件不一定叫default.conf,具体以自己容器内该地址下文件名字为准

3.修改default.conf【配置文件】

主要需要修改ip

server {
    listen       80;
    listen  [::]:80;
    server_name  ip;# 需要修改为自己的ip

    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

4.准备docker-compose.yml文件

posts前面是服务器对外的端口,后面的是容器内的端口

version: '3.1'
services:
  nginx:
    restart: always
    image: nginx
    container_name: nginx
    ports:
      - 5082:80
    volumes:
      # 本机目录:容器内目录
      - /data/nginx/docker_nginx/conf.d/:/etc/nginx/conf.d
      - /data/nginx/docker_nginx/html:/usr/share/nginx/html
      - /data/nginx/docker_nginx/logs:/var/log/nginx

5、访问nginx

在地址栏输入ip:端口

比如按照我的配置,我的是 218.75.105.125:5082/

出现内容,表示配置成功

三、问题与解答

1.ip和端口

在配置文件中修改ip和端口之后,在docker.compose.yml中端口一定要对应,冒号前面是服务器对外的端口(也就是你要访问的端口),冒号后面的是容器内的端口,需要与你在配置文件中修改的端口一致(尽量选择默认80)

2.访问ip+端口失败

检查是否是防火墙没有开启对应的接口

# 查看防火墙状态
systemctl status firewalld

#查看防火墙放行端口号
firewall-cmd --list-ports

#添加放行端口号60022
firewall-cmd --zone=public --add-port=60022/tcp --permanent

#重启防火墙
systemctl restart firewalld

查看容器内部ip地址

docker inspect e59d18a16a78 | grep IPAddress     
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",

curl 172.17.0.2

这个时候直接就链接不上

修改配置方法

1.进入nginx容器
可先 docker ps 查看容器ID或名称

docker exec -it 容器名或id /bin/bash        #进入容器

2.下载vim
因为容器是与本地隔绝的,所以我们要先安装vim

apt-get update        #更新包管理
apt-get install vim -y   #安装vim

3.vim修改配置

vim /etc/nginx/nginx.conf

 

posted @ 2023-04-28 15:08  在路上的白羊  阅读(282)  评论(0编辑  收藏  举报