Linux 시스템 IO 모델 요약 Nginx 컴파일 설치 및 기본 구성

Linux 시스템 IO 모델 요약 Nginx 컴파일 설치 및 기본 구성

1. Linux 시스템 IO 모델

1. IO의 개념

Linux 세계의 모든 것은 파일이고 소켓, 파이프, 터미널 등은 모두 파일입니다. Linux 시스템의 파일은 일련의 이진 스트림으로도 이해할 수 있습니다. 정보 교환 과정에서 이러한 이진 스트림을 보내고받는 작업은 I / O 작업 (입력 및 출력)이며, 가장 일반적인 작업은 디스크 IO와 네트워크 IO입니다.

2. 커널 공간과 사용자 공간

Linux 시스템은 메모리 공간을 커널 공간과 사용자 공간의 두 부분으로 나눕니다. 커널 코드와 데이터는 커널 공간에 저장되어 권한있는 명령을 실행하고 하드웨어 액세스와 같은 외부 서비스 인터페이스를 제공 할 수 있습니다. 사용자 공간에 저장되는 것은 사용자 프로그램의 코드와 데이터이며 권한이없는 명령 만 실행할 수 있습니다.

디스크 파일 읽기 및 쓰기, 네트워크 인터페이스에서 데이터 읽기 및 쓰기 등과 같은 모든 시스템 리소스 관리는 커널 공간에서 수행됩니다. 사용자의 응용 프로그램은 이러한 작업을 직접 수행 할 수 없으며 커널에서 제공하는 인터페이스를 통해서만 이러한 작업을 완료 할 수 있습니다.

4. 시스템 IO 모델

시스템 IO 모델을 이해하기위한 예로 데이터를 읽는 사용자 프로그램을 사용하십시오. 사용자는 디스크 장치에 직접 접근 할 수있는 권한이 없기 때문에 커널을 통해서만 가능합니다. 커널이 디스크에서 사용자가 필요로하는 데이터를 읽을 때, 커널 공간과 사용자 공간 사이의 엄격한 격리에 의해 제한되며, 커널 공간의 메모리 데이터를 사용자 공간의 프로세스 메모리로 복사해야합니다. 간단히 말해서 I / O는 커널이 디스크에서 커널 공간으로 데이터를 읽은 다음 커널 공간의 메모리 데이터를 사용자 공간의 프로세스 메모리로 복사하는 전체 프로세스입니다. 시스템 IO에는 동기식, 비동기식, 차단 및 비 차단의 네 가지 모델이 있습니다.

  • 동기 비동기

    이벤트 처리의 메시지 통신 메커니즘, 즉 피 호출자가 사물의 처리 결과를 기다리는 동안 완료 알림을 제공하는지 여부에 중점을 둡니다. 동기식 : 사용자 프로세스가 요청을 호출 한 후 커널은 알림 메커니즘을 제공하지 않습니다. 즉, 파일 IO 처리가 완료된 후 사용자 프로세스에 알림이 전송되지 않으며 사용자 프로세스는 처리가 완료되었는지 커널에 요청해야합니다. 비동기식 : 비동기식 : 사용자 프로세스가 요청을 호출 한 후 커널은 호출이 처리 된 후 사용자 프로세스에 호출 결과를 반환합니다. Nginx는 비동기식입니다.

  • 차단 / 비 차단

    결과가 반환되기를 기다리기 전에 호출자의 상태에주의하십시오. 차단 : 차단은 IO 작업이 완전히 완료되어 사용자 공간으로 돌아 가야 함을 의미합니다. 호출 결과가 반환되기 전에 호출자가 일시 중지되고 다른 작업을 수행 할 수 없습니다. Non-blocking : nonblocking은 IO 작업이 즉시 호출되어 사용자에게 상태 값을 반환하는 것을 의미합니다. IO 작업이 완전히 완료 될 때까지 기다릴 필요가 없습니다. 최종 호출 결과가 반환되기 전에 호출자는 일시 중지되지 않고 다른 작업을 수행 할 수 있습니다.

예를 들어 먹어 보자 : 나는 빵 10 개를 주문했다

  • 동기 및 비동기 :

    빵을 주문한 후 요리사가 다음과 같이 말했습니다.

    • 동기화 : 요리사는 빵을 만든 후 지정된 위치에 빵을 넣지 만, 빵을 만들기 전에 빵이 완성되었는지 확인해야합니다. 요리사는 빵을 만들지 않습니다.

    완료되면 알려주세요.

    • 비동기식 : 요리사가 빵을 만든 후 빵을 넣을 위치를 알려줍니다.
  • 차단 및 비 차단 ::

    빵을 주문한 후의 상태 :

    • 막힘 : 요리사가 빵을 만드는 동안 빵 접시 앞에서 기다리고 있었는데 다른 일을 할 수 없습니다.

    • Non-blocking : 빵을 주문한 후 쇼핑이나 구매와 같은 다른 작업을 할 수 있습니다.
  • IO 모델 조합 :

    • 동기식 차단 : 빵을 주문한 후에는 다른 작업을 할 수없고 빵이 다되었는지도 모르겠습니다. 기다리다가 요리사에게 몇 번이고 물어봐야합니다.

    아니.

    • 동기식 논 블로킹 : 빵을 주문한 후에는 다른 일을 할 수 있지만 오랫동안 다른 일을 할 수 없습니다. 그래도 빵이 잘되었는지 모르겠 기 때문에

    나는 요리사가 잘되었는지 몇 번이고 기다리고 기다리며 시간을 내서 다른 일을 할 수 밖에 없습니다.

    • 비동기식 차단 : 빵을 주문한 후에는 다른 일을 할 수 없지만 빵이 만들어지면 요리사가 알려줄 것입니다. 즉, 빵을 몇 번이고 요리 할 필요가 없습니다.

    끝났어?

    • 비동기식 비 차단 : 빵을 주문한 후에는 다른 일을 할 수 있고, 빵이 만들어진 후에 요리사가 알려줄 것이기 때문에 항상 다른 일을 할 수 있습니다.

5. Unix 시스템의 다섯 가지 네트워크 IO 모델과 Apache의 세 가지 작업 모드

UNIX 시스템에는 5 개의 네트워크 IO 모델이 있습니다.

  • 동기 차단 IO 모델 (blocking IO) : 차단 IO 모델은 가장 간단한 IO 모델입니다. 커널이 IO 작업을 수행 할 때 사용자 스레드가 차단됩니다.
  • 동기식 비 차단 I / O 모델 (비 차단 IO) : 애플리케이션 프로세스가 커널에 IO 요청을 보낸 후 커널이 응답하기를 기다리고있었습니다. 요청 된 IO 작업을 처리하는 커널이 IO 결과를 즉시 반환 할 수없는 경우 프로세스는 더 이상 기다리지 않고 다른 프로세스를 계속합니다. 요청하지만 일정 시간 후에 커널 IO가 완료되었는지 확인하는 프로세스가 여전히 필요합니다.
  • IO 멀티플렉싱 : 시스템 커널은 I / O 데이터를 버퍼링하고 단일 프로세스가 여러 파일 설명자를 모니터링 할 수 있도록합니다. 설명자가 준비되면 프로그램에 해당 읽기 및 쓰기 작업을 수행하도록 알릴 수 있습니다.
    • Linux 운영 체제에서는 모든 것이 파일로 추상화됩니다. 그러면 애플리케이션이 시스템의 다양한 파일에 어떻게 대응합니까? 파일 설명자 (파일 설명자, fd라고 함)가 등장했습니다. 응용 프로그램이 커널에 파일을 열거 나 만들도록 요청하면 커널은 열거 나 만든 파일에 해당하는 파일 설명자를 반환합니다.
    • select, poll 및 epoll은 Linux 시스템에서 IO 멀티플렉싱 모델의 기능적 실현입니다. 선택, 폴링 및 epoll은 읽기 및 쓰기 이벤트가 준비되고 읽기 및 쓰기 프로세스가 차단 된 후 모두 읽기 및 쓰기를 담당해야하므로 기본적으로 동기식 I / O입니다.
    • Apache prefork 모드는 기본 프로세스 + 다중 프로세스 / 단일 스레드 + 선택 모드이며 Apache 작업 모드는 기본 프로세스 + 다중 프로세스 / 다중 스레드 + 폴 모드입니다.
  • Signal-driven IO (signal-driven IO) : 사용자 프로세스는 sigaction 시스템 호출을 통해 신호 처리기를 등록한 다음 프로세스가 계속 하향 실행될 수 있습니다. IO 작업이 준비되면 커널이이를 알리고 SIGIO 신호 처리기를 실행하도록 트리거합니다. , 그런 다음 커널 공간에서 사용자 공간으로 사용자 프로세스에 필요한 데이터를 복사하십시오.
    • Apache 이벤트 모드는 기본 프로세스 + 다중 프로세스 / 다중 스레드 + 신호 구동 모드입니다.
  • 비동기 (비 차단) IO (비동기 IO) : 사용자 프로세스가 aio_read 시스템 호출을 수행 한 후 커널 데이터가 준비되었는지 여부에 관계없이 사용자 프로세스로 직접 돌아가고 사용자 모드 프로세스는 다른 작업을 수행 할 수 있으며 소켓 데이터가 준비 될 때까지 기다립니다. , 커널은 데이터를 프로세스에 직접 복사 한 다음 커널에서 프로세스로 알림을 보냅니다. 비동기식 비 차단 IO의 두 단계에서 프로세스는 비 차단입니다.

둘째, Nginx 기본 사항

1. Ubuntu 18.04.5 시스템 최적화

# vim /etc/security/limits.conf   #在文件后补追加
#root账户的资源软限制和硬限制
root soft core unlimited
root hard core unlimited
root soft nproc 1000000
root hard nproc 1000000
root soft nofile 1000000
root hard nofile 1000000
root soft memlock 32000
root hard memlock 32000
root soft msgqueue 8192000
root hard msgqueue 8192000
#其他账户的资源软限制和硬限制
* soft core unlimited
* hard core unlimited
* soft nproc 1000000
* hard nproc 1000000
* soft nofile 1000000
* hard nofile 1000000
* soft memlock 32000
* hard memlock 32000
* soft msgqueue 8192000
# vim /etc/sysctl.conf      #在文件后补追加
# Controls source route verification
net.ipv4.conf.default.rp_filter = 1
net.ipv4.ip_nonlocal_bind = 1
net.ipv4.ip_forward = 1

# Do not accept source routing
net.ipv4.conf.default.accept_source_route = 0

# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 0

# Controls whether core dumps will append the PID to the core filename.
# Useful for debugging multi-threaded applications.
kernel.core_uses_pid = 1

# Controls the use of TCP syncookies
net.ipv4.tcp_syncookies = 1

# Disable netfilter on bridges.
net.bridge.bridge-nf-call-ip6tables = 0
net.bridge.bridge-nf-call-iptables = 0
net.bridge.bridge-nf-call-arptables = 0

# Controls the default maxmimum size of a mesage queue
kernel.msgmnb = 65536

# # Controls the maximum size of a message, in bytes
kernel.msgmax = 65536

# Controls the maximum shared segment size, in bytes
kernel.shmmax = 68719476736

# # Controls the maximum number of shared memory segments, in pages
kernel.shmall = 4294967296

# TCP kernel paramater
net.ipv4.tcp_mem = 786432 1048576 1572864
net.ipv4.tcp_rmem = 4096 87380 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_sack = 1

# socket buffer
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 262144
net.core.somaxconn = 20480
net.core.optmem_max = 81920

# TCP conn net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_syn_retries = 3
net.ipv4.tcp_retries1 = 3
net.ipv4.tcp_retries2 = 15

# tcp conn reuse
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_tw_reuse = 0
net.ipv4.tcp_tw_recycle = 0
net.ipv4.tcp_fin_timeout = 1
net.ipv4.tcp_max_tw_buckets = 20000
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syncookies = 1

# keepalive conn
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.ip_local_port_range = 10001 65000

# swap
vm.overcommit_memory = 0
vm.swappiness = 10

#net.ipv4.conf.eth1.rp_filter = 0
#net.ipv4.conf.lo.arp_ignore = 1
#net.ipv4.conf.lo.arp_announce = 2
#net.ipv4.conf.all.arp_ignore = 1
#net.ipv4.conf.all.arp_announce = 2

# reboot

2. Nginx 컴파일 및 설치

2.1 운영 체제 소프트웨어 버전 정보

4.15.0-112-generic # 113-Ubuntu SMP 7 월 9 일 목요일 23:41:39 UTC 2020 x86_64 x86_64 x86_64 GNU / Linux

2.2 nginx 소스 코드 얻기

공식 웹 사이트 : http://nginx.org/ , 페이지 오른쪽에 다운로드 항목이 있습니다.

image-20201118205917571

image-20201118210054867

2.3 환경 준비 컴파일 및 설치
  • nginx 계정 만들기
# groupadd -g 2020 nginx
# useradd -u 2020 -g 2020 -r -s /bin/bash nginx
  • Nginx 디렉토리 권한 설정
# mkdir -p /app/nginx
# chown -R nginx:nginx /app
  • 설치 매개 변수 편집 및 정의
# mkdir  /app
# tar xvf nginx-1.18.0.tar.gz
# cd nginx-1.18.0
# ./configure --help

  --help                             print this message

  --prefix=PATH                      set installation prefix
  --sbin-path=PATH                   set nginx binary pathname
  --modules-path=PATH                set modules path
  --conf-path=PATH                   set nginx.conf pathname
  --error-log-path=PATH              set error log pathname
  --pid-path=PATH                    set nginx.pid pathname
  --lock-path=PATH                   set nginx.lock pathname

  --user=USER                        set non-privileged user for
                                     worker processes
  --group=GROUP                      set non-privileged group for
                                     worker processes

  --build=NAME                       set build name
  --builddir=DIR                     set build directory

  --with-select_module               enable select module
  --without-select_module            disable select module
  --with-poll_module                 enable poll module
  --without-poll_module              disable poll module

  --with-threads                     enable thread pool support

  --with-file-aio                    enable file AIO support

  --with-http_ssl_module             enable ngx_http_ssl_module
  --with-http_v2_module              enable ngx_http_v2_module
  --with-http_realip_module          enable ngx_http_realip_module
  --with-http_addition_module        enable ngx_http_addition_module
  --with-http_xslt_module            enable ngx_http_xslt_module
  --with-http_xslt_module=dynamic    enable dynamic ngx_http_xslt_module
  --with-http_image_filter_module    enable ngx_http_image_filter_module
  --with-http_image_filter_module=dynamic
                                     enable dynamic ngx_http_image_filter_module
  --with-http_geoip_module           enable ngx_http_geoip_module
  --with-http_geoip_module=dynamic   enable dynamic ngx_http_geoip_module
  --with-http_sub_module             enable ngx_http_sub_module
  --with-http_dav_module             enable ngx_http_dav_module
  --with-http_flv_module             enable ngx_http_flv_module
  --with-http_mp4_module             enable ngx_http_mp4_module
  --with-http_gunzip_module          enable ngx_http_gunzip_module
  --with-http_gzip_static_module     enable ngx_http_gzip_static_module
  --with-http_auth_request_module    enable ngx_http_auth_request_module
  --with-http_random_index_module    enable ngx_http_random_index_module
  --with-http_secure_link_module     enable ngx_http_secure_link_module
  --with-http_degradation_module     enable ngx_http_degradation_module
  --with-http_slice_module           enable ngx_http_slice_module
  --with-http_stub_status_module     enable ngx_http_stub_status_module

  --without-http_charset_module      disable ngx_http_charset_module
  --without-http_gzip_module         disable ngx_http_gzip_module
  --without-http_ssi_module          disable ngx_http_ssi_module
  --without-http_userid_module       disable ngx_http_userid_module
  --without-http_access_module       disable ngx_http_access_module
  --without-http_auth_basic_module   disable ngx_http_auth_basic_module
  --without-http_mirror_module       disable ngx_http_mirror_module
  --without-http_autoindex_module    disable ngx_http_autoindex_module
  --without-http_geo_module          disable ngx_http_geo_module
  --without-http_map_module          disable ngx_http_map_module
  --without-http_split_clients_module disable ngx_http_split_clients_module
  --without-http_referer_module      disable ngx_http_referer_module
  --without-http_rewrite_module      disable ngx_http_rewrite_module
  --without-http_proxy_module        disable ngx_http_proxy_module
  --without-http_fastcgi_module      disable ngx_http_fastcgi_module
  --without-http_uwsgi_module        disable ngx_http_uwsgi_module
  --without-http_scgi_module         disable ngx_http_scgi_module
  --without-http_grpc_module         disable ngx_http_grpc_module
  --without-http_memcached_module    disable ngx_http_memcached_module
  --without-http_limit_conn_module   disable ngx_http_limit_conn_module
  --without-http_limit_req_module    disable ngx_http_limit_req_module
  --without-http_empty_gif_module    disable ngx_http_empty_gif_module
  --without-http_browser_module      disable ngx_http_browser_module
  --without-http_upstream_hash_module
                                     disable ngx_http_upstream_hash_module
  --without-http_upstream_ip_hash_module
                                     disable ngx_http_upstream_ip_hash_module
  --without-http_upstream_least_conn_module
                                     disable ngx_http_upstream_least_conn_module
  --without-http_upstream_random_module
                                     disable ngx_http_upstream_random_module
  --without-http_upstream_keepalive_module
                                     disable ngx_http_upstream_keepalive_module
  --without-http_upstream_zone_module
                                     disable ngx_http_upstream_zone_module

  --with-http_perl_module            enable ngx_http_perl_module
  --with-http_perl_module=dynamic    enable dynamic ngx_http_perl_module
  --with-perl_modules_path=PATH      set Perl modules path
  --with-perl=PATH                   set perl binary pathname

  --http-log-path=PATH               set http access log pathname
  --http-client-body-temp-path=PATH  set path to store
                                     http client request body temporary files
  --http-proxy-temp-path=PATH        set path to store
                                     http proxy temporary files
  --http-fastcgi-temp-path=PATH      set path to store
                                     http fastcgi temporary files
  --http-uwsgi-temp-path=PATH        set path to store
                                     http uwsgi temporary files
  --http-scgi-temp-path=PATH         set path to store
                                     http scgi temporary files

  --without-http                     disable HTTP server
  --without-http-cache               disable HTTP cache

  --with-mail                        enable POP3/IMAP4/SMTP proxy module
  --with-mail=dynamic                enable dynamic POP3/IMAP4/SMTP proxy module
  --with-mail_ssl_module             enable ngx_mail_ssl_module
  --without-mail_pop3_module         disable ngx_mail_pop3_module
  --without-mail_imap_module         disable ngx_mail_imap_module
  --without-mail_smtp_module         disable ngx_mail_smtp_module

  --with-stream                      enable TCP/UDP proxy module
  --with-stream=dynamic              enable dynamic TCP/UDP proxy module
  --with-stream_ssl_module           enable ngx_stream_ssl_module
  --with-stream_realip_module        enable ngx_stream_realip_module
  --with-stream_geoip_module         enable ngx_stream_geoip_module
  --with-stream_geoip_module=dynamic enable dynamic ngx_stream_geoip_module
  --with-stream_ssl_preread_module   enable ngx_stream_ssl_preread_module
  --without-stream_limit_conn_module disable ngx_stream_limit_conn_module
  --without-stream_access_module     disable ngx_stream_access_module
  --without-stream_geo_module        disable ngx_stream_geo_module
  --without-stream_map_module        disable ngx_stream_map_module
  --without-stream_split_clients_module
                                     disable ngx_stream_split_clients_module
  --without-stream_return_module     disable ngx_stream_return_module
  --without-stream_upstream_hash_module
                                     disable ngx_stream_upstream_hash_module
  --without-stream_upstream_least_conn_module
                                     disable ngx_stream_upstream_least_conn_module
  --without-stream_upstream_random_module
                                     disable ngx_stream_upstream_random_module
  --without-stream_upstream_zone_module
                                     disable ngx_stream_upstream_zone_module

  --with-google_perftools_module     enable ngx_google_perftools_module
  --with-cpp_test_module             enable ngx_cpp_test_module

  --add-module=PATH                  enable external module
  --add-dynamic-module=PATH          enable dynamic external module

  --with-compat                      dynamic modules compatibility

  --with-cc=PATH                     set C compiler pathname
  --with-cpp=PATH                    set C preprocessor pathname
  --with-cc-opt=OPTIONS              set additional C compiler options
  --with-ld-opt=OPTIONS              set additional linker options
  --with-cpu-opt=CPU                 build for the specified CPU, valid values:
                                     pentium, pentiumpro, pentium3, pentium4,
                                     athlon, opteron, sparc32, sparc64, ppc64

  --without-pcre                     disable PCRE library usage
  --with-pcre                        force PCRE library usage
  --with-pcre=DIR                    set path to PCRE library sources
  --with-pcre-opt=OPTIONS            set additional build options for PCRE
  --with-pcre-jit                    build PCRE with JIT compilation support

  --with-zlib=DIR                    set path to zlib library sources
  --with-zlib-opt=OPTIONS            set additional build options for zlib
  --with-zlib-asm=CPU                use zlib assembler sources optimized
                                     for the specified CPU, valid values:
                                     pentium, pentiumpro

  --with-libatomic                   force libatomic_ops library usage
  --with-libatomic=DIR               set path to libatomic_ops library sources

  --with-openssl=DIR                 set path to OpenSSL library sources
  --with-openssl-opt=OPTIONS         set additional build options for OpenSSL

  --with-debug                       enable debug logging

공식 웹 사이트 문서를 통해 nginx 모듈의 기능 설명을 확인할 수 있습니다.

image-20201118211423656

image-20201118211504074

  • 소프트웨어 환경 준비 컴파일 및 설치

    • apt-get 업그레이드 # apt update
    • gcc 설치 # apt install -y gcc
    • C ++ 종속성 라이브러리 설치 # apt install build-essential # apt install libtool
    • pcre 종속성 라이브러리 설치 # apt install libpcre3 libpcre3-dev
    • zlib 종속성 라이브러리 설치 # apt install zlib1g-dev
    • SSL 종속성 라이브러리 설치 #apt install libssl-dev
  • 사용자 지정 설치 매개 변수 결정

    공식 웹 사이트 http://nginx.org/en/docs/configure.html에서 사용자 정의 매개 변수의 의미와 최종 설치 옵션 매개 변수를 확인하십시오.

    $ sudo ./configure --prefix = / app / nginx --user = nginx --group = nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module- with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module

2.4 컴파일 및 설치 시작
  • 구성

    #  ./configure --prefix=/app/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
    
  • 하다

    # make
  • 설치하다

    # make install
  • 컴파일 및 설치 후 nginx 시작

    # /app/nginx/sbin/nginx
  • 컴파일되고 설치된 nginx 웹 인터페이스에 액세스합니다.

    image-20201118230138056

3. Nginx의 공통 구성 및 최적화

3.1 환경 매개 변수에 nginx 경로 추가
root@dl-homework:~# pwd
/root
root@dl-homework:~# ll
total 64
drwx------  5 root root  4096 Nov 19 10:03 ./
drwxr-xr-x 24 root root  4096 Nov 18 21:05 ../
-rw-------  1 root root 10257 Nov 19 09:46 .bash_history
-rw-r--r--  1 root root  3140 Nov 19 09:44 .bashrc
drwx------  2 root root  4096 Nov 14 11:28 .cache/
drwx------  3 root root  4096 Nov 14 11:28 .gnupg/
-rw-r--r--  1 root root   148 Aug 17  2015 .profile
drwxr-xr-x  2 root root  4096 Nov 14 11:55 .vim/
-rw-------  1 root root 12836 Nov 19 09:45 .viminfo
-rw-r--r--  1 root root    17 Nov 19 09:45 .vimrc
-rw-------  1 root root   134 Nov 19 10:03 .Xauthority
root@dl-homework:~# vim .bashrc

100 export PATH=$PATH:/app/nginx/sbin   #在文件最后一行添加

# . .bashrc
3.2 시작 스크립트를 사용하여 자체 시작 nginx 서비스 실현
# cd /lib/systemd/system
# vim nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking   
PIDFile=/run/nginx.pid   #要与nginx.conf里面的配置保持一致
ExecStart=/app/nginx/sbin/nginx -c /app/nginx/conf/nginx.conf  #更改为nginx的实际路径
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID

[Install]
WantedBy=multi-user.target

# systemctl daemon-reload

# systemctl start nginx.service
## systemctl enable nginx.service
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /lib/systemd/system/nginx.service.
3.3 Nginx 기본 구성

모든 매개 변수는 nginx.com 웹 사이트의 문서에서 찾을 수 있습니다. nginx.conf의 기본 매개 변수 :

# cd /app/nginx/conf
# grep -v "#"  nginx.conf |grep -v "^$"
worker_processes  1;
pid        /run/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
# vim /app/nginx/conf/nginx.conf

 worker_processes  auto;       #进程数量
 worker_cpu_affinity  auto;    #进程与CPU绑定

 pid        /run/nginx.pid;    #文件位置要与nginx.service里的配置保持一致

 worker_rlimit_nofile   65535;   #允许一个工作进程打开的文件数

 events {
      worker_connections  102400;  #单个进程最大并发连接数
      accept_mutex on;   #避免群惊
      multi_accept on;   #允许接受多个新连接
  }

  http {
    include       mime.types;   #支持的文件类型
    default_type  application/octet-stream;  #无法识别就下载文件

     sendfile        on;  #实现文件零拷贝MMAP
     tcp_nopush      on;  #合并请求后统一发送给客户端,降低服务器端负载,配合sendfile使用
     gzip  on;  #开启文件压缩
     keepalive_timeout  65;  #长连接时间65秒
     server {
        listen       80;
        server_name  localhost;
        charset utf-8;   #更改中文字符集
        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

  }

# nginx -t
nginx: the configuration file /app/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /app/nginx/conf/nginx.conf test is successful
# systemctl reload nginx.service
3.4 PC 사이트 및 모바일 사이트 생성
# mkdir /app/nginx/conf/conf.d
# vim /app/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name pc.home.net;

    location / {
        root /app/nginx/html/pc;
        }
    }

# vim /app/nginx/conf/conf.d/mobile.conf 
server {
    listen 80;
    server_name mobile.home.net;

    location / {
        root /app/nginx/html/mobile;
        }
    }

# mkdir /app/nginx/html/{pc,mobile}
# echo "mobile web" > /app/nginx/html/mobile/index.html
# echo "pc web" > /app/nginx/html/pc/index.html

# nginx -t
nginx: the configuration file /app/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /app/nginx/conf/nginx.conf test is successful

# systemctl reload nginx.service

Windows 시스템에서 C : \ Windows \ System32 \ drivers \ etc \ hosts 파일을 수정하고 172.20.200.138 pc.home.net mobile.home.net을 추가하고 다음 사이트를 방문하십시오.

image-20201119194403714

image-20201119194444533

추천

출처blog.51cto.com/12302225/2552422