From 1f40398194dea04e0ac2c8374f40e62c0e2e7922 Mon Sep 17 00:00:00 2001 From: Marcos Freitas Date: Mon, 20 Jul 2020 23:37:39 -0300 Subject: [PATCH 1/2] :wip: refactoring image with alpine and multiple containers --- .docker/nginx/Dockerfile | 42 +++++++++++ .docker/nginx/nginx.conf | 70 ++++++++++++++++++ .docker/nginx/templates/app.conf.template | 6 ++ .../snippets/base-vhosts.conf.template | 59 +++++++++++++++ .../snippets/cache-directives.conf.template | 52 +++++++++++++ .../fastcgi-extra-php-params.conf.template | 3 + .../snippets/http-server.conf.template | 24 ++++++ .../snippets/performance.conf.template | 70 ++++++++++++++++++ .../templates/snippets/php.conf.template | 12 +++ .../snippets/security-http.conf.template | 16 ++++ .../snippets/security-locations.conf.template | 31 ++++++++ .docker/php-fpm/Dockerfile | 19 +++++ docker-compose.yml | 74 +++++++++++++++++++ 13 files changed, 478 insertions(+) create mode 100644 .docker/nginx/Dockerfile create mode 100755 .docker/nginx/nginx.conf create mode 100755 .docker/nginx/templates/app.conf.template create mode 100755 .docker/nginx/templates/snippets/base-vhosts.conf.template create mode 100755 .docker/nginx/templates/snippets/cache-directives.conf.template create mode 100755 .docker/nginx/templates/snippets/fastcgi-extra-php-params.conf.template create mode 100755 .docker/nginx/templates/snippets/http-server.conf.template create mode 100755 .docker/nginx/templates/snippets/performance.conf.template create mode 100755 .docker/nginx/templates/snippets/php.conf.template create mode 100755 .docker/nginx/templates/snippets/security-http.conf.template create mode 100755 .docker/nginx/templates/snippets/security-locations.conf.template create mode 100644 .docker/php-fpm/Dockerfile create mode 100644 docker-compose.yml diff --git a/.docker/nginx/Dockerfile b/.docker/nginx/Dockerfile new file mode 100644 index 0000000..9e8f905 --- /dev/null +++ b/.docker/nginx/Dockerfile @@ -0,0 +1,42 @@ +# @version 4.0.0 +# Configures NGINX . + +FROM nginx:1.19.1-alpine +LABEL maintainer="marcosfreitas@c4network.com.br" + +#RUN apk add --no-cache shadow &&\ +# usermod -u 1000 nginx + +#USER nginx + +EXPOSE 80 +# @todo not prepared to work with SSL connections yet +EXPOSE 443 + +RUN cd / &&\ + wget https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh &&\ + chmod +x wait-for-it.sh + +RUN rm /etc/nginx/nginx.conf +RUN rm /etc/nginx/conf.d/default.conf + +# From the context of this Dockerfile +ADD nginx.conf /etc/nginx/nginx.conf + +#ADD conf/vhost-app.conf /etc/nginx/sites-available/app + +# @bug permission bug +#RUN mkdir -p /etc/nginx/sites-enabled &&\ +# mkdir -p /etc/nginx/templates &&\ +# chmod 751 -R /etc/nginx &&\ +# ls -l /etc/nginx/ &&\ +# ln -s /etc/nginx/sites-available/app /etc/nginx/sites-enabled/app + +# @bug problem with relative paths +#RUN rm -rf /var/www/html +#VOLUME /../../www /var/www/html +#VOLUME /../..//.docker/nginx/templates /etc/nginx/templates + +# @todo make entrypoints and custon configurations + +CMD ["nginx", "-g", "daemon off;"] \ No newline at end of file diff --git a/.docker/nginx/nginx.conf b/.docker/nginx/nginx.conf new file mode 100755 index 0000000..31586e8 --- /dev/null +++ b/.docker/nginx/nginx.conf @@ -0,0 +1,70 @@ +# @author Marcos Freitas +# @version 2.0.0 + +# worker_processes shoult be the same as the number of cores of the processor +# worker_connection can be multiplied by worker_processes to improve performance +# Check out Nginx' documentation for more details. + +user nginx; +worker_processes auto; +pid /run/nginx.pid; +include /etc/nginx/modules-enabled/*.conf; + +# number of file descriptors used for nginx +# the limit for the maximum FDs on the server is usually set by the OS. +# if you don't set FD's then OS settings will be used which is by default 2000 +worker_rlimit_nofile 50000; + +events { + # determines how much clients will be served per worker + # max clients = worker_connections * worker_processes + # max clients is also limited by the number of socket connections available on the system (~64k) + worker_connections 20000; + + # optimized to serve many clients with each thread, essential for linux -- for testing environment + # use epoll; + + # accept as many connections as possible, may flood worker connections if set too low -- for testing environment + # multi_accept on; +} + +http { + + ## + # Basic Settings + ## + + # enabled for small downloads only into performance snippet + sendfile off; + tcp_nopush on; + tcp_nodelay on; + types_hash_max_size 2048; + + include conf.d/snippets/security-http.conf; + + # @todo server_names_hash_bucket_size 64; + # @todo server_name_in_redirect off; + + include /etc/nginx/mime.types; + default_type application/octet-stream; + + ## + # Logging Settings + ## + + log_format main '$remote_addr - $remote_user [$time_local] "$request" ' + '$status $body_bytes_sent "$http_referer" ' + '"$http_user_agent" "$http_x_forwarded_for"'; + + access_log /var/log/nginx/access.log main; + error_log /var/log/nginx/error.log; + + ## + # Virtual Host Configs + ## + + include /etc/nginx/conf.d/*.conf; + + # @bug failed permissions + #include /etc/nginx/sites-enabled/*; +} diff --git a/.docker/nginx/templates/app.conf.template b/.docker/nginx/templates/app.conf.template new file mode 100755 index 0000000..169e690 --- /dev/null +++ b/.docker/nginx/templates/app.conf.template @@ -0,0 +1,6 @@ +# @author Marcos Freitas + +# the following configuration snippet implements a 1‑second caching period for responses with a 200 OK status code. +fastcgi_cache_path /tmp/cache keys_zone=APPLICATION:10m levels=1:2 inactive=60m max_size=500m use_temp_path=off; + +include conf.d/snippets/http-server.conf; \ No newline at end of file diff --git a/.docker/nginx/templates/snippets/base-vhosts.conf.template b/.docker/nginx/templates/snippets/base-vhosts.conf.template new file mode 100755 index 0000000..7adf28f --- /dev/null +++ b/.docker/nginx/templates/snippets/base-vhosts.conf.template @@ -0,0 +1,59 @@ +# main files to serve +index index.php index.html; + +location / { + + allow all; + + # First attempt to serve request as file, then + # as directory, then fall back to displaying a 404. + #try_files $uri $uri/ =404; + try_files $uri $uri/ /index.php?$query_string; + + # Set CSP Rules + # https://content-security-policy.com/ + # ajusta o conjunto de domínios permitidos para carregamento de scripts externos + # aplica os métodos aceitos para aplicar estilos e executar scripts no site + # add_header Content-Security-Policy default-src 'self' data: 'unsafe-inline' 'unsafe-eval' *.googleapis.com *.gstatic.com *google-analytics.com + +} + +# pass PHP scripts to FastCGI server + +include conf.d/snippets/php.conf; + +# if the laravel project is located into a subdirectory + +# location ^~ /app { +# alias /var/www/PATH_TO_SUBDIRECTORY/www/public; +# try_files $uri $uri/ @sub_directory; + +# location ~ \.php$ { +# include conf.d/snippets/fastcgi-php.conf; +# fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; +# } +# } + +# location @sub_directory { +# rewrite /app/(.*)$ /app/index.php?/$1 last; +# } +# -- + +# deny access to .htaccess files, if Apache's document root +# concurs with nginx's one + +location ~ /\.ht { + deny all; +} + +# disallow the access to all files and folders with dot at the beginning +location ~ /\.(?!well-known\/) { + deny all; +} + +# blocks old WordPress xmlrpc feature to prevent authentication attacks in this file +location = /xmlrpc.php { + deny all; + access_log off; + log_not_found off; +} \ No newline at end of file diff --git a/.docker/nginx/templates/snippets/cache-directives.conf.template b/.docker/nginx/templates/snippets/cache-directives.conf.template new file mode 100755 index 0000000..c117736 --- /dev/null +++ b/.docker/nginx/templates/snippets/cache-directives.conf.template @@ -0,0 +1,52 @@ +set $skip_cache 0; + +# POST requests and urls with a query string should always go to PHP +if ($request_method = POST) { + set $skip_cache 1; +} +if ($query_string != "") { + set $skip_cache 1; +} + +# Wordpress Cache configuration + + +# Don't cache uris containing the following segments +if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") { + set $skip_cache 1; +} + +# Don't use the cache for logged in users or recent commenters +if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") { + set $skip_cache 1; +} + +# "punching a hole" through the cache +# To support Pragma: no-cache sent by clients and force touch the resource without cache +# and Acessible as http://www.example.com/?nocache=true +fastcgi_cache_bypass $skip_cache $http_pragma $cookie_nocache $arg_nocache; +fastcgi_no_cache $skip_cache; + +# https://www.nginx.com/blog/nginx-caching-guide/#proxy_cache_path +add_header X-Cache-Status $upstream_cache_status; + +# @info using predefined keys_zone at app.conf +fastcgi_cache APPLICATION; + +fastcgi_cache_revalidate on; + +# 200 301 302 statuses are cached by 1 minute +fastcgi_cache_valid 1m; +# 404 status +fastcgi_cache_valid 404 5s; + +# delivering Cached Content When the Origin is Down +fastcgi_cache_use_stale error timeout invalid_header updating http_500 http_503; +fastcgi_cache_background_update on; + +# only one request at a time will be allowed to populate a new cache element +fastcgi_cache_key "$scheme$request_method$host$request_uri"; +fastcgi_cache_lock on; + +# add header to show if the response is cached +add_header rt-Fastcgi-Cache $upstream_cache_status; diff --git a/.docker/nginx/templates/snippets/fastcgi-extra-php-params.conf.template b/.docker/nginx/templates/snippets/fastcgi-extra-php-params.conf.template new file mode 100755 index 0000000..6c1659c --- /dev/null +++ b/.docker/nginx/templates/snippets/fastcgi-extra-php-params.conf.template @@ -0,0 +1,3 @@ +# @changelog +# increased memory_limit directive +fastcgi_param PHP_VALUE "memory_limit=512M;\n allow_url_fopen=on;\n file_uploads=on;\n upload_tmp_dir=\"/tmp\";\n upload_max_filesize=80M;\n post_max_size=80M;\n max_execution_time=600;\n max_input_time=600;\n session.cookie_httponly=on;\n display_startup_errors=off;\n display_errors=off;\n html_errors=off;\n error_reporting=on;\n log_errors=on;\n error_log=\"/var/log/nginx/php_error.log\";"; \ No newline at end of file diff --git a/.docker/nginx/templates/snippets/http-server.conf.template b/.docker/nginx/templates/snippets/http-server.conf.template new file mode 100755 index 0000000..4a2fd00 --- /dev/null +++ b/.docker/nginx/templates/snippets/http-server.conf.template @@ -0,0 +1,24 @@ +# @info default http:80 server + +server { + listen ${NGINX_PORT} default_server; + listen [::]:${NGINX_PORT} default_server; + + root /var/www/html/public; + + server_name ${NGINX_HOST}; + + # to SSL permanent redirect for all request on port 80 + #server_name _; + #return 301 https://$host$request_uri; + + # load general security configurations + include conf.d/snippets/security-locations.conf; + + # Performance configuration + include conf.d/snippets/cache-directives.conf; + include conf.d/snippets/performance.conf; + + # base configurations of virtual host + include conf.d/snippets/base-vhosts.conf; +} \ No newline at end of file diff --git a/.docker/nginx/templates/snippets/performance.conf.template b/.docker/nginx/templates/snippets/performance.conf.template new file mode 100755 index 0000000..6a426a8 --- /dev/null +++ b/.docker/nginx/templates/snippets/performance.conf.template @@ -0,0 +1,70 @@ +# Start: Size Limits and Buffer Overflows +client_body_buffer_size 2K; +client_header_buffer_size 2k; + +# -- control for posts/upload +# should be equal to fastcgi param +client_max_body_size 80M; + +large_client_header_buffers 4 16k; + +# Start: Timeouts +client_body_timeout 10; +client_header_timeout 10; +keepalive_timeout 15; +send_timeout 10; + +# Gzip Compression +# disabled because use of ssl +gzip on; +gzip_comp_level 2; +gzip_min_length 1000; +gzip_proxied expired no-cache no-store private auth; +# gzip_vary on; +# gzip_proxied any; +# gzip_comp_level 6; +# gzip_buffers 16 8k; +# gzip_http_version 1.1; +gzip_types text/plain text/xml text/css application/json application/javascript application/xml application/xml+rss; + + +# Static file caching +location ~* .(js|json)$ { + # Indicate that the resource may be cached by public caches like web caches for instance, + # if set to 'private' the resource may only be cached by client's browser. + add_header Cache-Control public; + # Indicate that the resource can be cached for 24 hours + expires 24h; +} + +location ~* .(css)$ { + add_header Cache-Control public; + # Equivalent to above: + # Indicate that the resource can be cached for 86400 seconds (24 hours) + expires 86400; + + # Add an ETag header with an identifier that can be stored by the client + etag on; +} + +location ~* \.(?:ico|gif|jpe?g|png|svg|woff|woff22|ttf)$ { + add_header Cache-Control public; + expires 30d; + # Indicate that the browser can serve a compressed version of these resources + add_header Vary Accept-Encoding; + # Indicate that the resource must be revalidated at each access + add_header Cache-Control must-revalidate; + access_log off; + etag on; + # Set the OS file cache. + open_file_cache max=3000 inactive=120s; + open_file_cache_valid 60s; + open_file_cache_min_uses 2; + open_file_cache_errors off; +} + +# medium downloadable files that can be sent directly without be copied to buffer +location ~* .(mp3|mp4|pdf)$ { + sendfile on; + sendfile_max_chunk 80m; +} \ No newline at end of file diff --git a/.docker/nginx/templates/snippets/php.conf.template b/.docker/nginx/templates/snippets/php.conf.template new file mode 100755 index 0000000..0e3d7fc --- /dev/null +++ b/.docker/nginx/templates/snippets/php.conf.template @@ -0,0 +1,12 @@ +# cache-directives.conf already have bypasses + +location ~ \.php$ { + #include conf.d/snippets/fastcgi-php.conf; + include fastcgi_params; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + + include conf.d/snippets/fastcgi-extra-php-params.conf; + + # With php-fpm (or other unix sockets): + fastcgi_pass ${PHP_HOST}:${PHP_PORT}; +} \ No newline at end of file diff --git a/.docker/nginx/templates/snippets/security-http.conf.template b/.docker/nginx/templates/snippets/security-http.conf.template new file mode 100755 index 0000000..212206b --- /dev/null +++ b/.docker/nginx/templates/snippets/security-http.conf.template @@ -0,0 +1,16 @@ +# @info part of http block at nginx.conf + +# https://medium.freecodecamp.org/nginx-rate-limiting-in-a-nutshell-128fe9e0126c +limit_req_zone $binary_remote_addr zone=generic:10m rate=10r/s; +# @todo need review +#limit_req zone=generic burst=20 nodelay; + +# Control maximum number of simultaneous connections for one session i.e. +# restricts the amount of connections from a single ip address +# @todo @experimental limit_conn addr 10; + +# these configurations affects the log records +proxy_set_header Host $http_host; +proxy_set_header X-Real-IP $remote_addr; +proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; +proxy_set_header X-Forwarded-Proto $scheme; diff --git a/.docker/nginx/templates/snippets/security-locations.conf.template b/.docker/nginx/templates/snippets/security-locations.conf.template new file mode 100755 index 0000000..851b3fb --- /dev/null +++ b/.docker/nginx/templates/snippets/security-locations.conf.template @@ -0,0 +1,31 @@ +# @info part of server block +# @todo change the name of this file + +# Disable show nginx version +server_tokens off; + +# removing php header +fastcgi_hide_header X-Powered-By; + +# Avoid clickjacking +add_header X-Frame-Options SAMEORIGIN; + +# Disable content-type sniffing on some browsers +add_header X-Content-Type-Options nosniff; + +# Enable the Cross-site scripting (XSS) filter +add_header X-XSS-Protection "1; mode=block"; + +# Disable directory listing +autoindex off; + +# Set cookies secure +#set_cookie_flag HttpOnly secure; + +# Enable CORS +add_header Access-Control-Allow-Origin '*'; + +# By removing the ETag header, you disable caches and browsers from being able to validate files, +# so they are forced to rely on your Cache-Control and Expires header. +# Basically you can remove If-Modified-Since and If-None-Match requests and their 304 Not Modified Responses. +etag off; \ No newline at end of file diff --git a/.docker/php-fpm/Dockerfile b/.docker/php-fpm/Dockerfile new file mode 100644 index 0000000..a290d14 --- /dev/null +++ b/.docker/php-fpm/Dockerfile @@ -0,0 +1,19 @@ +FROM php:7.4-fpm-alpine + +ARG APP_ENVIROMENT + + +# @info fix permissions +# Use the default production configuration +RUN apk add --no-cache shadow &&\ + usermod -u 1000 www-data &&\ + mv "$PHP_INI_DIR/php.ini-$APP_ENVIROMENT" "$PHP_INI_DIR/php.ini" + + +EXPOSE 9000 + +WORKDIR /var/www + +USER www-data + +ENTRYPOINT ["php-fpm"] \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..093a169 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,74 @@ +version: "3.7" + +services: + + nginx: + build: + context: .docker/nginx + tty: true + restart: always + networks: + - backend + - database + ports: + - "80:80" + - "443:443" + volumes: + - ./www:/var/www/html + - ./.docker/nginx/templates:/etc/nginx/templates + environment: + - NGINX_HOST=localhost + - NGINX_PORT=80 + - PHP_HOST=php + - PHP_PORT=9000 + - DB_HOST=database + - DB_PORT=3306 + depends_on: + - database + command: ["./wait-for-it.sh", "database:3306", "-t=90"] + + php: + build: + context: .docker/php-fpm + args: + APP_ENVIROMENT: ${APP_ENVIROMENT} + tty: true + networks: + - backend + ports: + - 9000 + volumes: + - "./www:/var/www/html" + + redis: + image: redis:6-alpine + ports: + - 6379 + networks: + - backend + + database: + image: mysql:latest + environment: + MYSQL_DATABASE: ${COMPOSE_PROJECT_NAME} + MYSQL_ROOT_PASSWORD: 123 + MYSQL_USER: docker + MYSQL_PASSWORD: 123 + networks: + - database + ports: + - "3306:3306" + volumes: + - dbdata:/var/lib/mysql + +networks: + backend: + driver: bridge + database: + driver: bridge + +volumes: + dbdata: + driver: local + labels: + mf.project.name: ${COMPOSE_PROJECT_NAME} \ No newline at end of file From fa5cfa775ec990c751e927f533cabe8c1fba70c3 Mon Sep 17 00:00:00 2001 From: Marcos Freitas Date: Mon, 2 Nov 2020 19:57:47 -0300 Subject: [PATCH 2/2] =?UTF-8?q?Estrutura=20reorganizada=20em=20templates?= =?UTF-8?q?=20que=20trabalham=20com=20vari=C3=A1veis=20de=20ambiente;=20Im?= =?UTF-8?q?agens=20base=20trocadas=20para=20alpine;=20Remo=C3=A7=C3=A3o=20?= =?UTF-8?q?de=20arquivos=20e=20scripts=20depreciados.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .docker/nginx/Dockerfile | 44 ++-- .docker/nginx/nginx.conf | 7 +- .../snippets/cache-directives.conf.template | 13 -- .../snippets/http-server.conf.template | 2 +- .../app.conf.template => vhost-app.conf} | 0 .docker/php-fpm/Dockerfile | 22 +- .../laravel-initial-configurations.sh | 19 +- .../scripts/set-right-permissions-by-path.sh | 21 ++ .env | 2 + .gitignore | 3 + Dockerfile | 34 --- README.md | 33 ++- docker-compose.yml | 47 +++- ...te-and-fix-initial-user-authentication.sql | 2 - src/server/configurations.sh | 124 ---------- src/server/helpers.sh | 211 ------------------ src/server/nginx/nginx-install.sh | 42 ---- src/server/nginx/nginx.conf | 68 ------ src/server/nginx/php/php-install.sh | 29 --- src/server/nginx/snippets/base-vhosts.conf | 59 ----- .../nginx/snippets/cache-directives.conf | 49 ---- .../snippets/fastcgi-extra-php-params.conf | 3 - src/server/nginx/snippets/http-server.conf | 24 -- src/server/nginx/snippets/performance.conf | 70 ------ src/server/nginx/snippets/php.conf | 12 - src/server/nginx/snippets/security-http.conf | 16 -- .../nginx/snippets/security-locations.conf | 31 --- src/server/nginx/vhost-app.conf | 6 - 28 files changed, 150 insertions(+), 843 deletions(-) rename .docker/nginx/{templates/app.conf.template => vhost-app.conf} (100%) rename {src/laravel => .docker/src/scripts}/laravel-initial-configurations.sh (53%) create mode 100755 .docker/src/scripts/set-right-permissions-by-path.sh create mode 100755 .env create mode 100755 .gitignore delete mode 100644 Dockerfile delete mode 100755 src/database/sql/create-and-fix-initial-user-authentication.sql delete mode 100644 src/server/configurations.sh delete mode 100644 src/server/helpers.sh delete mode 100755 src/server/nginx/nginx-install.sh delete mode 100755 src/server/nginx/nginx.conf delete mode 100644 src/server/nginx/php/php-install.sh delete mode 100755 src/server/nginx/snippets/base-vhosts.conf delete mode 100755 src/server/nginx/snippets/cache-directives.conf delete mode 100755 src/server/nginx/snippets/fastcgi-extra-php-params.conf delete mode 100755 src/server/nginx/snippets/http-server.conf delete mode 100755 src/server/nginx/snippets/performance.conf delete mode 100755 src/server/nginx/snippets/php.conf delete mode 100755 src/server/nginx/snippets/security-http.conf delete mode 100755 src/server/nginx/snippets/security-locations.conf delete mode 100755 src/server/nginx/vhost-app.conf diff --git a/.docker/nginx/Dockerfile b/.docker/nginx/Dockerfile index 9e8f905..ec7286f 100644 --- a/.docker/nginx/Dockerfile +++ b/.docker/nginx/Dockerfile @@ -1,9 +1,10 @@ # @version 4.0.0 # Configures NGINX . -FROM nginx:1.19.1-alpine +FROM nginx:1.19-alpine LABEL maintainer="marcosfreitas@c4network.com.br" +# @todo change user to not run as root #RUN apk add --no-cache shadow &&\ # usermod -u 1000 nginx @@ -13,30 +14,39 @@ EXPOSE 80 # @todo not prepared to work with SSL connections yet EXPOSE 443 -RUN cd / &&\ - wget https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh &&\ - chmod +x wait-for-it.sh +# @bug misconfiguration, should be tested +#RUN cd / &&\ +# wget https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh &&\ +# chmod +x wait-for-it.sh -RUN rm /etc/nginx/nginx.conf -RUN rm /etc/nginx/conf.d/default.conf +RUN apk update && apk add --no-cache openssl shadow bash wait4ports &&\ + rm /etc/nginx/nginx.conf &&\ + rm /etc/nginx/conf.d/default.conf # From the context of this Dockerfile -ADD nginx.conf /etc/nginx/nginx.conf +ADD /nginx/nginx.conf /etc/nginx/nginx.conf -#ADD conf/vhost-app.conf /etc/nginx/sites-available/app +#ENV DOCKERIZE_VERSION v0.6.1 +#RUN wget https://github.com/jwilder/dockerize/releases/download/${DOCKERIZE_VERSION}/dockerize-alpine-linux-amd64-${DOCKERIZE_VERSION}.tar.gz \ +# && tar -C /usr/local/bin -xzvf dockerize-alpine-linux-amd64-${DOCKERIZE_VERSION}.tar.gz \ +# && rm dockerize-alpine-linux-amd64-${DOCKERIZE_VERSION}.tar.gz -# @bug permission bug -#RUN mkdir -p /etc/nginx/sites-enabled &&\ -# mkdir -p /etc/nginx/templates &&\ -# chmod 751 -R /etc/nginx &&\ -# ls -l /etc/nginx/ &&\ -# ln -s /etc/nginx/sites-available/app /etc/nginx/sites-enabled/app +# @bug problem with folder's permissions +RUN mkdir -p /etc/nginx/sites-enabled &&\ + mkdir -p /etc/nginx/sites-available &&\ + chmod 751 -R /etc/nginx; + +ADD /nginx/vhost-app.conf /etc/nginx/sites-available/app + +RUN ln -s /etc/nginx/sites-available/app /etc/nginx/sites-enabled/app + +RUN ls -l /etc/nginx/conf.d; +RUN ls -l /etc/nginx/; # @bug problem with relative paths #RUN rm -rf /var/www/html #VOLUME /../../www /var/www/html -#VOLUME /../..//.docker/nginx/templates /etc/nginx/templates - -# @todo make entrypoints and custon configurations +#VOLUME /../../.docker/nginx/templates /etc/nginx/templates +#RUN ls /etc/nginx/templates/snippets; CMD ["nginx", "-g", "daemon off;"] \ No newline at end of file diff --git a/.docker/nginx/nginx.conf b/.docker/nginx/nginx.conf index 31586e8..45d9ba3 100755 --- a/.docker/nginx/nginx.conf +++ b/.docker/nginx/nginx.conf @@ -40,7 +40,7 @@ http { tcp_nodelay on; types_hash_max_size 2048; - include conf.d/snippets/security-http.conf; + include /etc/nginx/conf.d/snippets/security-http.conf; # @todo server_names_hash_bucket_size 64; # @todo server_name_in_redirect off; @@ -63,8 +63,5 @@ http { # Virtual Host Configs ## - include /etc/nginx/conf.d/*.conf; - - # @bug failed permissions - #include /etc/nginx/sites-enabled/*; + include /etc/nginx/sites-enabled/*; } diff --git a/.docker/nginx/templates/snippets/cache-directives.conf.template b/.docker/nginx/templates/snippets/cache-directives.conf.template index c117736..6f62595 100755 --- a/.docker/nginx/templates/snippets/cache-directives.conf.template +++ b/.docker/nginx/templates/snippets/cache-directives.conf.template @@ -8,19 +8,6 @@ if ($query_string != "") { set $skip_cache 1; } -# Wordpress Cache configuration - - -# Don't cache uris containing the following segments -if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") { - set $skip_cache 1; -} - -# Don't use the cache for logged in users or recent commenters -if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") { - set $skip_cache 1; -} - # "punching a hole" through the cache # To support Pragma: no-cache sent by clients and force touch the resource without cache # and Acessible as http://www.example.com/?nocache=true diff --git a/.docker/nginx/templates/snippets/http-server.conf.template b/.docker/nginx/templates/snippets/http-server.conf.template index 4a2fd00..245ad4c 100755 --- a/.docker/nginx/templates/snippets/http-server.conf.template +++ b/.docker/nginx/templates/snippets/http-server.conf.template @@ -4,7 +4,7 @@ server { listen ${NGINX_PORT} default_server; listen [::]:${NGINX_PORT} default_server; - root /var/www/html/public; + root ${NGINX_ROOT}; server_name ${NGINX_HOST}; diff --git a/.docker/nginx/templates/app.conf.template b/.docker/nginx/vhost-app.conf similarity index 100% rename from .docker/nginx/templates/app.conf.template rename to .docker/nginx/vhost-app.conf diff --git a/.docker/php-fpm/Dockerfile b/.docker/php-fpm/Dockerfile index a290d14..a2caca1 100644 --- a/.docker/php-fpm/Dockerfile +++ b/.docker/php-fpm/Dockerfile @@ -1,19 +1,31 @@ FROM php:7.4-fpm-alpine +LABEL maintainer="marcosfreitas@c4network.com.br" ARG APP_ENVIROMENT +EXPOSE 9000 + +# Added script to easy install PHP extensions + +COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/bin/ # @info fix permissions # Use the default production configuration -RUN apk add --no-cache shadow &&\ +RUN apk update && apk add --no-cache shadow bash composer &&\ usermod -u 1000 www-data &&\ - mv "$PHP_INI_DIR/php.ini-$APP_ENVIROMENT" "$PHP_INI_DIR/php.ini" + mv "$PHP_INI_DIR/php.ini-$APP_ENVIROMENT" "$PHP_INI_DIR/php.ini" &&\ + install-php-extensions mysqli pdo_mysql bcmath gd &&\ + php-fpm -m +COPY /src/scripts/ /usr/share/.docker/src/scripts -EXPOSE 9000 +RUN chmod +x /usr/share/.docker/src/scripts/*.sh &&\ + mkdir -p /var/www/html &&\ + bash /usr/share/.docker/src/scripts/set-right-permissions-by-path.sh /var/www/ &&\ + bash /usr/share/.docker/src/scripts/set-right-permissions-by-path.sh /var/www/html -WORKDIR /var/www +WORKDIR /var/www/html USER www-data -ENTRYPOINT ["php-fpm"] \ No newline at end of file +ENTRYPOINT [ "/usr/share/.docker/src/scripts/laravel-initial-configurations.sh" ] \ No newline at end of file diff --git a/src/laravel/laravel-initial-configurations.sh b/.docker/src/scripts/laravel-initial-configurations.sh similarity index 53% rename from src/laravel/laravel-initial-configurations.sh rename to .docker/src/scripts/laravel-initial-configurations.sh index 2fe95e5..f8b529b 100755 --- a/src/laravel/laravel-initial-configurations.sh +++ b/.docker/src/scripts/laravel-initial-configurations.sh @@ -1,17 +1,18 @@ #!/usr/bin/env bash -echo "-- Running composer install"; - cd /var/www/html; -composer install; +if [[ -f 'composer.json' ]]; then + echo "-- Running composer install"; + composer install; +fi; CONTAINER_ALREADY_STARTED="CONTAINER_ALREADY_RAN_ONCE" -if [ ! -e $CONTAINER_ALREADY_STARTED ]; then +if [[ ! -e $CONTAINER_ALREADY_STARTED && -f 'artisan' ]]; then touch $CONTAINER_ALREADY_STARTED - echo "-- Container first time for its first time" + echo "-- Running this container first its very first time" chmod a+rw -R /var/www/; @@ -32,9 +33,11 @@ if [ ! -e $CONTAINER_ALREADY_STARTED ]; then chmod a+rw -R /var/www/; else - echo "-- Container already run. No need to be reconfigured" + echo "-- Container already run, no need to be reconfigured or Laravel is not installed." fi -service nginx start && service php7.2-fpm start && /bin/bash +echo "-- Services running"; + +php-fpm; -echo "-- Services running"; \ No newline at end of file +service php-fpm status; \ No newline at end of file diff --git a/.docker/src/scripts/set-right-permissions-by-path.sh b/.docker/src/scripts/set-right-permissions-by-path.sh new file mode 100755 index 0000000..bc4a6b8 --- /dev/null +++ b/.docker/src/scripts/set-right-permissions-by-path.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +# Run as: +# bash this-script.sh /var/www and again passing your project folder /var/www/project-path + +FILE_PATH=$1; + +if [[ ! -d "$FILE_PATH" ]]; then + echo 'Path argument not defined'; + exit; +fi; + +chmod 775 ${FILE_PATH} -R && \ +chmod 2775 ${FILE_PATH} -R && \ +chown -R www-data:www-data ${FILE_PATH} -R; + +if [[ ! -z $(ls -A .) ]]; then + cd ${FILE_PATH} && find * -type d -exec chmod -R 775 {} \; && find * -type f -exec chmod -R 664 {} \; +else + echo 'Path is empty, not running commands for children.'; +fi; \ No newline at end of file diff --git a/.env b/.env new file mode 100755 index 0000000..0a997ec --- /dev/null +++ b/.env @@ -0,0 +1,2 @@ +COMPOSE_PROJECT_NAME=SKINNY_HOSTS +APP_ENVIROMENT=development \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..50ef3e3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__OLD +!/.docker +www \ No newline at end of file diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index be193f7..0000000 --- a/Dockerfile +++ /dev/null @@ -1,34 +0,0 @@ -# @version 3.7.5 -# Dockerfile para configuração geral do servidor. Ele vai executar alguns comandos iniciais e scripts de instalação do servidor web e php-fpm - -FROM ubuntu:18.04 -LABEL maintainer="marcosvsfreitas@gmail.com" - -EXPOSE 80 -EXPOSE 443 - -# Desativa modo interativo para não interromper o processo de build da imagem -ENV DEBIAN_FRONTEND noninteractive - -# Ajsute de idioma para a imagem quando o container é executado -RUN apt-get update -RUN apt-get install -y locales locales-all sudo gnupg2 - -ENV LC_ALL en_US.UTF-8 -ENV LANG en_US.UTF-8 -ENV LANGUAGE en_US.UTF-8 - -# Copiando scripts de configuração geral -ADD /src/ /docker/src - -RUN chmod +x /docker/src/server/helpers.sh -RUN chmod +x /docker/src/server/configurations.sh -RUN chmod +x /docker/src/laravel/laravel-initial-configurations.sh - -RUN cd /docker/src/server/ && bash configurations.sh - -ENTRYPOINT ["/docker/src/laravel/laravel-initial-configurations.sh"] - -WORKDIR /var/www/html - -CMD service nginx start && service php7.2-fpm start && /bin/bash \ No newline at end of file diff --git a/README.md b/README.md index 9a22dd8..0b86c72 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,32 @@ -# Laravel Host em docker - para testes -Imagem pré-configurada com nginx e php-fpm 7.2 para efeito de testes. Não utilize em produção. +# Imagens Alpine com NGINX, PHP-FPM e MySQL para hospedagem Laravel em Docker (Em desenvolvimento) +**Os arquivos Laravel devem ser instalados previamente na pasta www.** -[![Docker Build Status](https://img.shields.io/docker/automated/marcosfreitas/docker-laravel-host?style=for-the-badge)](https://hub.docker.com/r/marcosfreitas/docker-laravel-host/) \ No newline at end of file +Este projeto está equipado com docker-compose, ao clonar você pode executar desta forma: + +`docker-compose up -d` + +A imagem construída do projeto Laravel foi publicada no Docker HUB: + +https://hub.docker.com/r/marcosfreitas/skinny-hosts/ + +[![Docker Build Status](https://img.shields.io/docker/automated/marcosfreitas/skinny-hosts?style=for-the-badge)](https://hub.docker.com/r/marcosfreitas/skinny-hosts/) + +# Detalhes dos Containeres + +### NGINX +O serviço de NGINX possui configurações customizadas a partir dos templates em **.docker/nginx**. +Ele depende do serviço de php e se comunica pelo host e porta passados nas variáveis de ambiente. + +### PHP-FPM +O serviço de PHP-FPM não possui configurações customizadas, mas a construção do container prepara as permissões corretas de arquivos e a instalação do Laravel de acordo com os scripts Bash nas pasta **.docker/src/scripts**. + +### MySQL +O MySQL possui a versão 8+ com implementação de fallback de autenticação para versão 5.7. + + +## Detalhes + +Na raiz do repositório há o arquivo .env que define o nome do projeto que reflete nas configurações do Laravel, prefixo de containeres e nome de Banco de dados, além do ambiente (development ou production) para o php-fpm. + +O arquivo docker-compose.yml implementa outras variáveis de ambiente utilizadas pelo dockerize. \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 093a169..52da2ad 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -3,10 +3,12 @@ version: "3.7" services: nginx: + build: - context: .docker/nginx + context: .docker + dockerfile: nginx/Dockerfile tty: true - restart: always + restart: unless-stopped networks: - backend - database @@ -17,6 +19,7 @@ services: - ./www:/var/www/html - ./.docker/nginx/templates:/etc/nginx/templates environment: + - NGINX_ROOT=/var/www/html/public - NGINX_HOST=localhost - NGINX_PORT=80 - PHP_HOST=php @@ -25,30 +28,47 @@ services: - DB_PORT=3306 depends_on: - database - command: ["./wait-for-it.sh", "database:3306", "-t=90"] + command: bash -c 'wait4ports -q -t 60 -s 10 tcp://database:3306 tcp://php:9000; /docker-entrypoint.sh nginx -g "daemon off;"' php: + build: - context: .docker/php-fpm + context: .docker + dockerfile: php-fpm/Dockerfile args: APP_ENVIROMENT: ${APP_ENVIROMENT} tty: true + restart: always networks: - backend + - database ports: - 9000 volumes: - "./www:/var/www/html" + environment: + - DB_HOST=database + - DB_PORT=3306 + - APP_ENVIROMENT=${APP_ENVIROMENT} + - PROJECT_NAME=${COMPOSE_PROJECT_NAME} + - DB_USERNAME=docker + - DB_PASSWORD=123 + - REDIS_HOST='' + - REDIS_PASSWORD='' + - REDIS_PORT='' - redis: - image: redis:6-alpine - ports: - - 6379 - networks: - - backend + #redis: + + # image: redis:6-alpine + # ports: + # - 6379 + # networks: + # - backend database: + image: mysql:latest + command: --default-authentication-plugin=mysql_native_password environment: MYSQL_DATABASE: ${COMPOSE_PROJECT_NAME} MYSQL_ROOT_PASSWORD: 123 @@ -60,15 +80,20 @@ services: - "3306:3306" volumes: - dbdata:/var/lib/mysql + healthcheck: + test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"] + timeout: 20s networks: + backend: driver: bridge database: driver: bridge volumes: + dbdata: driver: local labels: - mf.project.name: ${COMPOSE_PROJECT_NAME} \ No newline at end of file + sh.project.name: ${COMPOSE_PROJECT_NAME} \ No newline at end of file diff --git a/src/database/sql/create-and-fix-initial-user-authentication.sql b/src/database/sql/create-and-fix-initial-user-authentication.sql deleted file mode 100755 index 1f47b5f..0000000 --- a/src/database/sql/create-and-fix-initial-user-authentication.sql +++ /dev/null @@ -1,2 +0,0 @@ -CREATE USER docker@'%' identified with mysql_native_password by '123'; -grant All privileges on *.* to docker@'%'; diff --git a/src/server/configurations.sh b/src/server/configurations.sh deleted file mode 100644 index f3b92e8..0000000 --- a/src/server/configurations.sh +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/env bash - -author="Marcos Freitas" -version="3.10.0" -manual_version="1.0.3" - -# global variables - -DIR="${BASH_SOURCE[0]}" -if [[ ! -d "$DIR" ]]; then DIR="$PWD"; fi - -# including helpers.sh file -source "$DIR/helpers.sh" - -# Add necessary repos -function AddRepositories() { - { - AptUpdate 'upgrade' - - Separator "Ativando repositórios extras para o Ubuntu 16.04 64 Bits" - - apt-get install -y software-properties-common apt-transport-https gnupg2 - - Separator "ativando os repositórios Universe e Multiverse" ${LIGHT_GREEN} - - add-apt-repository "deb http://archive.ubuntu.com/ubuntu/ bionic universe multiverse" && - echo -ne "\n" | add-apt-repository ppa:ondrej/php && - echo -ne "\n" | add-apt-repository ppa:ondrej/nginx && - apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 4F4EA0AAE5267A6C && - apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E5267A6C - - AptUpdate 'upgrade' - - apt-get -y auto-remove - - } || { - - Count $1 'AddRepositories' - - } -} - -# Add and Enable virtual host files -# For each site hosted in this server, you should create a individual file for its virtual host -# - into the folder "/etc/nginx/sites-available", then enable the site creating a simbolic link into "/etc/nginx/site-enabled" -function AddVirtualHostFiles() { - { - - Separator "Ajustando arquivo do VirtualHost do projeto:" - - cp $DIR/nginx/vhost-app.conf /etc/nginx/sites-available/app - mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bkp - cp $DIR/nginx/nginx.conf /etc/nginx/nginx.conf - - cp -r $DIR/nginx/snippets /etc/nginx - - ln -s /etc/nginx/sites-available/app /etc/nginx/sites-enabled/ - - } || { - Count $1 'AddVirtualHostFiles' - } -} - -# Configuring virtual host folders -# protect folders giving access only to the process of nginx -function AdjustVirtualHostFolders() { - { - Separator "Ajustando diretórios do VirtualHost do projeto:" - - # site - mkdir -p /var/www/html && - chmod 755 /var/www && - chmod 2755 /var/www/html && - chown -R www-data:www-data /var/www - - # app - mkdir -p /var/www/app && - chmod 755 /var/www && - chmod 2755 /var/www/app && - chown -R www-data:www-data /var/www - - } || { - Count $1 'AdjustVirtualHostFolders' - } -} - -# Install some software dependencies packages -# @version 1.0.1 -function InstallSoftwareDependencies() { - { - Separator "Instalando dependências de software comuns durante o desenvolvimento" - - apt-get -y install composer - - export COMPOSER_HOME="$HOME/.config/composer" - - } || { - Count $1 'InstallSoftwareDependencies' - } -} - -Separator "For Ubuntu 18.04 64-Bit | Version $version based on 'Manual de Infraestrutura' $manual_version | Author: $author" ${CYAN} - -# self running all the instalation processes - -AptUpdate -AddExtraPackages 1 - -source "$DIR/nginx/nginx-install.sh" -source "$DIR/nginx/php/php-install.sh" - -# Calling all methods passing 1 as a initial value to counter - -InstallNginx 1 -AddVirtualHostFiles 1 -AdjustVirtualHostFolders 1 -ProtectProjectDirectories 1 - -AddRepositories 1 -InstallPHP 1 - -InstallSoftwareDependencies 1 - -Separator "Processo de configuração concluído aparentemente com sucesso ;)." ${CYAN} diff --git a/src/server/helpers.sh b/src/server/helpers.sh deleted file mode 100644 index f06fbc5..0000000 --- a/src/server/helpers.sh +++ /dev/null @@ -1,211 +0,0 @@ -#!/usr/bin/env bash - -f_version="2.7.0" -f_authors="Marcos Freitas"; - -# colors -# Black 0;30 Dark Gray 1;30 -# Red 0;31 Light Red 1;31 -# Green 0;32 Light Green 1;32 -# Brown/Orange 0;33 Yellow 1;33 -# Blue 0;34 Light Blue 1;34 -# Purple 0;35 Light Purple 1;35 -# Cyan 0;36 Light Cyan 1;36 -# Light Gray 0;37 White 1;37 - -RED="\033[0;31m"; -CYAN="\033[0;36m"; -YELLOW="\033[1;33m"; -LIGHT_GREEN="\033[1;32m"; - -# No Color -NC="\033[0m"; - -# script status -SCRIPT_STATUS=$? - -# run this script as sudo -if [[ $EUID -ne "0" ]]; then - sudo "${0}" "${@}"; -fi - -# -# Common functions used into configuration.sh files for All Images -# - -# Receive a current count number on position $1; -# Receive a function name on position $2; -# not using but $0 is the name of the script itself; -function Count() { - - # check if position $1 exists - if [ -z "$1" ]; then - echo "Expected param 1"; - exit 0; - fi - - if [ -z "$2" ]; then - echo "Expected param 2"; - exit 0; - fi - - if [ ${1} -ge 1 ]; then - count=$1; - fi - - if [ ${count} -le 3 ]; then - echo -e ${RED}; - printf "\nUma saída inesperada ocorreu durante a última instrução, mas tudo pode estar bem.\nDeseja executar novamente o processo $2?\n" - echo -e ${NC}; - read -n1 -r -p "Pressione S para continuar ou N para cancelar: " key - - # $key is empty when ENTER/SPACE is pressed - if [ "$key" = 'S' -o "$key" = 's' ]; then - echo -e ${CYAN}; - echo "Tentativa " ${count} " de 3..."; - echo -e ${NC}; - ${2} $((count += 1)); - else - return 1; - fi - - else - echo "Não foi possível realizar a operação em $2, abortando o processo"; - fi -} - -# receive the output string on position ${1} and a optional color on position ${2} -# version 1.1.0 -function Separator() { - echo ''; - echo ''; - - # if ${2} is empty - if [ -z "${2}" ]; then - echo -e ${YELLOW}; - else - echo -e ${2}; - fi - - echo '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'; - echo ' ' ${1}; - echo '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'; - echo -e ${NC}; - echo ''; - echo ''; -} - -# wait a key press to continue the process, by default the doesn't abort the script at all, only if passed the second argument as "abort" -# version 1.1.0 - Accepting arg 1 as message -# arg 2 as the expected_key_pressed for positive case -# arg 3 is the parameter to abort the entire script execution -# @info if global interactive_mode be false, input key won't be expected and always will continue, returning 1, be carefull with your outside logic when call this function. -function PressKeyToContinue() { - - if [ $interactive_mode == false ]; then - Separator "::: pulando..." ${YELLOW}; - return 1; - fi - - printf "\n"; - - question="Pressione S para continuar ou qualquer outra tecla para pular essa parte execução do script"; - expected_key_pressed='s'; - abort_script=false; - - if [ ! -z "$1" ]; then - question="${1}"; - fi - - if [ ! -z "$2" ]; then - expected_key_pressed="${2}"; - fi - - if [[ ! -z "$3" && "${3,,}" == "abort" ]]; then - # in case of a negative response, the script will abort the process - abort_script=true; - fi - - read -n1 -r -p "${question}: " key - - # "parameter expansion" transforming key to lowercase - # @info $key is empty when ENTER/SPACE is pressed - if [[ "${key,,}" == "${expected_key_pressed,,}" ]]; then - echo 1; - else - if [ $abort_script == true ]; then - exit 1; - fi - - # by default continue to the next step - echo 0; - fi -} - -# change values into configuration files. Receives $key $separator $value $file -# version 1.0.0 -function ChangeValueConfig(){ - { - Separator 'sed -i "s|\('${1}' *'${2}'*\).*|\1'${3}'|" '${4}';'; - sed -i "s|\('${1}' *'${2}'*\).*|\1'${3}'|" '${4}'; - } || { - Count ${1} 'ChangeValueConfig'; - } -} - -# @version 1.1.0 - Added arg 1 to receive "upgrade" command -function AptUpdate() { - - Separator "Buscando informações de atualização dos repositórios..." ${LIGHT_GREEN}; - - apt-get -y update; - - if [[ ! -z "$1" && "${1,,}" == "upgrade" ]]; then - Separator "Instalando novas atualizações de pacotes disponíveis..." ${LIGHT_GREEN}; - apt-get -y upgrade; - fi - -} - -function AddExtraPackages() { - { - Separator "Preparando pré-requisitos"; - - Separator "Instalando pacote de Idiomas Inglês:" ${LIGHT_GREEN}; - apt-get -y install language-pack-en; - - locale-gen "en_US.UTF-8" && localedef -v -c -i en_US -f UTF-8 en_US.UTF-8; - export LC_ALL=en_US.UTF-8 && export LANG=en_US.UTF-8 && export LANGUAGE=en_US.UTF-8; - - printf '\n[ Status dos locales do sistema ]\n'; - locale; - - Separator "Instalando o pacote wget para capturar o conteúdo de uma URL, o editor nano e o pacote unzip para manipular arquivos .zip e outros pacotes auxiliares" ${LIGHT_GREEN}; - apt-get -y install wget nano unzip curl tree; - - Separator "Instalando pacotes adicionais para a configuração do NGINX e PHP" ${LIGHT_GREEN}; - apt-get -y install tar bzip2 gcc; - - Separator "Instalando pacotes que auxiliam no gerenciamento e debug de conflitos de infraestrutura" ${LIGHT_GREEN}; - apt-get install -y net-tools; - - - } || { - Count ${1} 'AddExtraPackages'; - } -} - -function ProtectProjectDirectories() { - { - Separator "Protegendo os diretórios e arquivos do Projeto com as permissões CHMOD corretas"; - cd /var/www/; - find html -type d -exec chmod -R 755 {} \; && \ - find html -type f -exec chmod -R 644 {} \; - - } || { - Count ${1} 'ProtectProjectDirectories'; - } -} - - -Separator "Using functions.sh version $f_version | Authors: $f_authors" ${LIGHT_GREEN}; \ No newline at end of file diff --git a/src/server/nginx/nginx-install.sh b/src/server/nginx/nginx-install.sh deleted file mode 100755 index 8770fbb..0000000 --- a/src/server/nginx/nginx-install.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env bash - -# Install Nginx and enable it on UFW Firewall, also, protect with chmod its directory -# @version 1.1.0 - Added verification for existent NGINX installation -function InstallNginx() { - { - Separator "Instalando e Configurando o Servidor Nginx" - - if [[ -f /usr/sbin/nginx ]]; then - Separator "O NGINX já está instalado" ${YELLOW} - - #if [[ $(PressKeyToContinue "Pressione 's' para reinstalar ou qualquer outra tecla para pular esta parte: " "s") -eq 1 ]]; then - - Separator "Removendo a instalação do NGINX..." ${RED} - - apt-get purge nginx && InstallNginx - - # else - # return 1 - # fi - fi - - wget http://nginx.org/packages/keys/nginx_signing.key && - echo "deb http://nginx.org/packages/ubuntu/ bionic nginx" >>/etc/apt/sources.list && - echo "deb-src http://nginx.org/packages/ubuntu/ bionic nginx" >>/etc/apt/sources.list && apt-key add ./nginx_signing.key - - AptUpdate - - apt-get install -y nginx && systemctl enable nginx - - mkdir /etc/nginx/sites-available - mkdir /etc/nginx/sites-enabled - - service nginx stop - - Separator "Protegendo os diretórios de configuração do Nginx" ${LIGHT_GREEN} - chmod 0750 -R /etc/nginx/ - - } || { - Count $1 'InstallNginx' - } -} diff --git a/src/server/nginx/nginx.conf b/src/server/nginx/nginx.conf deleted file mode 100755 index 5daaedf..0000000 --- a/src/server/nginx/nginx.conf +++ /dev/null @@ -1,68 +0,0 @@ -# @author Marcos Freitas -# @version 2.0.0 - -# worker_processes shoult be the same as the number of cores of the processor -# worker_connection can be multiplied by worker_processes to improve performance -# Check out Nginx' documentation for more details. - -user www-data; -worker_processes auto; -pid /run/nginx.pid; -include /etc/nginx/modules-enabled/*.conf; - -# number of file descriptors used for nginx -# the limit for the maximum FDs on the server is usually set by the OS. -# if you don't set FD's then OS settings will be used which is by default 2000 -worker_rlimit_nofile 50000; - -events { - # determines how much clients will be served per worker - # max clients = worker_connections * worker_processes - # max clients is also limited by the number of socket connections available on the system (~64k) - worker_connections 20000; - - # optimized to serve many clients with each thread, essential for linux -- for testing environment - # use epoll; - - # accept as many connections as possible, may flood worker connections if set too low -- for testing environment - # multi_accept on; -} - -http { - - ## - # Basic Settings - ## - - # enabled for small downloads only into performance snippet - sendfile off; - tcp_nopush on; - tcp_nodelay on; - types_hash_max_size 2048; - - include snippets/security-http.conf; - - # @todo server_names_hash_bucket_size 64; - # @todo server_name_in_redirect off; - - include /etc/nginx/mime.types; - default_type application/octet-stream; - - ## - # Logging Settings - ## - - log_format main '$remote_addr - $remote_user [$time_local] "$request" ' - '$status $body_bytes_sent "$http_referer" ' - '"$http_user_agent" "$http_x_forwarded_for"'; - - access_log /var/log/nginx/access.log main; - error_log /var/log/nginx/error.log; - - ## - # Virtual Host Configs - ## - - #include /etc/nginx/conf.d/*.conf; - include /etc/nginx/sites-enabled/*; -} diff --git a/src/server/nginx/php/php-install.sh b/src/server/nginx/php/php-install.sh deleted file mode 100644 index 7488f5c..0000000 --- a/src/server/nginx/php/php-install.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -# Install PHP7.2-fpm and its extensions -function InstallPHP() { - { - - Separator "Instalando PHP 7.2 FPM e as principais extensões utilizadas" - - apt-get -y install php7.2-fpm - - service nginx restart - - # extensions - - apt-get -y install php7.2-mbstring - apt-get -y install php7.2-bcmath - apt-get -y install php7.2-xml - apt-get -y install php7.2-curl - apt-get -y install php7.2-mysql - apt-get -y install php7.2-gd - - # @bugfix failed restart because it wans't running - service php7.2-fpm stop && service php7.2-fpm start - service nginx restart - - } || { - Count $1 'InstallPHP' - } -} diff --git a/src/server/nginx/snippets/base-vhosts.conf b/src/server/nginx/snippets/base-vhosts.conf deleted file mode 100755 index 758501c..0000000 --- a/src/server/nginx/snippets/base-vhosts.conf +++ /dev/null @@ -1,59 +0,0 @@ -# main files to serve -index index.php index.html; - -location / { - - allow all; - - # First attempt to serve request as file, then - # as directory, then fall back to displaying a 404. - #try_files $uri $uri/ =404; - try_files $uri $uri/ /index.php?$query_string; - - # Set CSP Rules - # https://content-security-policy.com/ - # ajusta o conjunto de domínios permitidos para carregamento de scripts externos - # aplica os métodos aceitos para aplicar estilos e executar scripts no site - # add_header Content-Security-Policy default-src 'self' data: 'unsafe-inline' 'unsafe-eval' *.googleapis.com *.gstatic.com *google-analytics.com - -} - -# pass PHP scripts to FastCGI server - -include snippets/php.conf; - -# if the laravel project is located into a subdirectory - -# location ^~ /app { -# alias /var/www/PATH_TO_SUBDIRECTORY/www/public; -# try_files $uri $uri/ @sub_directory; - -# location ~ \.php$ { -# include snippets/fastcgi-php.conf; -# fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; -# } -# } - -# location @sub_directory { -# rewrite /app/(.*)$ /app/index.php?/$1 last; -# } -# -- - -# deny access to .htaccess files, if Apache's document root -# concurs with nginx's one - -location ~ /\.ht { - deny all; -} - -# disallow the access to all files and folders with dot at the beginning -location ~ /\.(?!well-known\/) { - deny all; -} - -# blocks old WordPress xmlrpc feature to prevent authentication attacks in this file -location = /xmlrpc.php { - deny all; - access_log off; - log_not_found off; -} \ No newline at end of file diff --git a/src/server/nginx/snippets/cache-directives.conf b/src/server/nginx/snippets/cache-directives.conf deleted file mode 100755 index d0157e9..0000000 --- a/src/server/nginx/snippets/cache-directives.conf +++ /dev/null @@ -1,49 +0,0 @@ -set $skip_cache 0; - -# POST requests and urls with a query string should always go to PHP -if ($request_method = POST) { - set $skip_cache 1; -} -if ($query_string != "") { - set $skip_cache 1; -} - -# Don't cache uris containing the following segments -if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") { - set $skip_cache 1; -} - -# Don't use the cache for logged in users or recent commenters -if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") { - set $skip_cache 1; -} - -# "punching a hole" through the cache -# To support Pragma: no-cache sent by clients and force touch the resource without cache -# and Acessible as http://www.example.com/?nocache=true -fastcgi_cache_bypass $skip_cache $http_pragma $cookie_nocache $arg_nocache; -fastcgi_no_cache $skip_cache; - -# https://www.nginx.com/blog/nginx-caching-guide/#proxy_cache_path -add_header X-Cache-Status $upstream_cache_status; - -# @info using predefined keys_zone at app.conf -fastcgi_cache APPLICATION; - -fastcgi_cache_revalidate on; - -# 200 301 302 statuses are cached by 1 minute -fastcgi_cache_valid 1m; -# 404 status -fastcgi_cache_valid 404 5s; - -# delivering Cached Content When the Origin is Down -fastcgi_cache_use_stale error timeout invalid_header updating http_500 http_503; -fastcgi_cache_background_update on; - -# only one request at a time will be allowed to populate a new cache element -fastcgi_cache_key "$scheme$request_method$host$request_uri"; -fastcgi_cache_lock on; - -# add header to show if the response is cached -add_header rt-Fastcgi-Cache $upstream_cache_status; diff --git a/src/server/nginx/snippets/fastcgi-extra-php-params.conf b/src/server/nginx/snippets/fastcgi-extra-php-params.conf deleted file mode 100755 index 6c1659c..0000000 --- a/src/server/nginx/snippets/fastcgi-extra-php-params.conf +++ /dev/null @@ -1,3 +0,0 @@ -# @changelog -# increased memory_limit directive -fastcgi_param PHP_VALUE "memory_limit=512M;\n allow_url_fopen=on;\n file_uploads=on;\n upload_tmp_dir=\"/tmp\";\n upload_max_filesize=80M;\n post_max_size=80M;\n max_execution_time=600;\n max_input_time=600;\n session.cookie_httponly=on;\n display_startup_errors=off;\n display_errors=off;\n html_errors=off;\n error_reporting=on;\n log_errors=on;\n error_log=\"/var/log/nginx/php_error.log\";"; \ No newline at end of file diff --git a/src/server/nginx/snippets/http-server.conf b/src/server/nginx/snippets/http-server.conf deleted file mode 100755 index b3d0559..0000000 --- a/src/server/nginx/snippets/http-server.conf +++ /dev/null @@ -1,24 +0,0 @@ -# @info default http:80 server - -server { - listen 80 default_server; - listen [::]:80 default_server; - - root /var/www/html/public; - - server_name localhost; - - # to SSL permanent redirect for all request on port 80 - #server_name _; - #return 301 https://$host$request_uri; - - # load general security configurations - include snippets/security-locations.conf; - - # Performance configuration - include snippets/cache-directives.conf; - include snippets/performance.conf; - - # base configurations of virtual host - include snippets/base-vhosts.conf; -} \ No newline at end of file diff --git a/src/server/nginx/snippets/performance.conf b/src/server/nginx/snippets/performance.conf deleted file mode 100755 index 6a426a8..0000000 --- a/src/server/nginx/snippets/performance.conf +++ /dev/null @@ -1,70 +0,0 @@ -# Start: Size Limits and Buffer Overflows -client_body_buffer_size 2K; -client_header_buffer_size 2k; - -# -- control for posts/upload -# should be equal to fastcgi param -client_max_body_size 80M; - -large_client_header_buffers 4 16k; - -# Start: Timeouts -client_body_timeout 10; -client_header_timeout 10; -keepalive_timeout 15; -send_timeout 10; - -# Gzip Compression -# disabled because use of ssl -gzip on; -gzip_comp_level 2; -gzip_min_length 1000; -gzip_proxied expired no-cache no-store private auth; -# gzip_vary on; -# gzip_proxied any; -# gzip_comp_level 6; -# gzip_buffers 16 8k; -# gzip_http_version 1.1; -gzip_types text/plain text/xml text/css application/json application/javascript application/xml application/xml+rss; - - -# Static file caching -location ~* .(js|json)$ { - # Indicate that the resource may be cached by public caches like web caches for instance, - # if set to 'private' the resource may only be cached by client's browser. - add_header Cache-Control public; - # Indicate that the resource can be cached for 24 hours - expires 24h; -} - -location ~* .(css)$ { - add_header Cache-Control public; - # Equivalent to above: - # Indicate that the resource can be cached for 86400 seconds (24 hours) - expires 86400; - - # Add an ETag header with an identifier that can be stored by the client - etag on; -} - -location ~* \.(?:ico|gif|jpe?g|png|svg|woff|woff22|ttf)$ { - add_header Cache-Control public; - expires 30d; - # Indicate that the browser can serve a compressed version of these resources - add_header Vary Accept-Encoding; - # Indicate that the resource must be revalidated at each access - add_header Cache-Control must-revalidate; - access_log off; - etag on; - # Set the OS file cache. - open_file_cache max=3000 inactive=120s; - open_file_cache_valid 60s; - open_file_cache_min_uses 2; - open_file_cache_errors off; -} - -# medium downloadable files that can be sent directly without be copied to buffer -location ~* .(mp3|mp4|pdf)$ { - sendfile on; - sendfile_max_chunk 80m; -} \ No newline at end of file diff --git a/src/server/nginx/snippets/php.conf b/src/server/nginx/snippets/php.conf deleted file mode 100755 index 9d3d5ca..0000000 --- a/src/server/nginx/snippets/php.conf +++ /dev/null @@ -1,12 +0,0 @@ -# cache-directives.conf already have bypasses - -location ~ \.php$ { - #include snippets/fastcgi-php.conf; - include fastcgi_params; - fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; - - include snippets/fastcgi-extra-php-params.conf; - - # With php-fpm (or other unix sockets): - fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; -} \ No newline at end of file diff --git a/src/server/nginx/snippets/security-http.conf b/src/server/nginx/snippets/security-http.conf deleted file mode 100755 index 212206b..0000000 --- a/src/server/nginx/snippets/security-http.conf +++ /dev/null @@ -1,16 +0,0 @@ -# @info part of http block at nginx.conf - -# https://medium.freecodecamp.org/nginx-rate-limiting-in-a-nutshell-128fe9e0126c -limit_req_zone $binary_remote_addr zone=generic:10m rate=10r/s; -# @todo need review -#limit_req zone=generic burst=20 nodelay; - -# Control maximum number of simultaneous connections for one session i.e. -# restricts the amount of connections from a single ip address -# @todo @experimental limit_conn addr 10; - -# these configurations affects the log records -proxy_set_header Host $http_host; -proxy_set_header X-Real-IP $remote_addr; -proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; -proxy_set_header X-Forwarded-Proto $scheme; diff --git a/src/server/nginx/snippets/security-locations.conf b/src/server/nginx/snippets/security-locations.conf deleted file mode 100755 index 851b3fb..0000000 --- a/src/server/nginx/snippets/security-locations.conf +++ /dev/null @@ -1,31 +0,0 @@ -# @info part of server block -# @todo change the name of this file - -# Disable show nginx version -server_tokens off; - -# removing php header -fastcgi_hide_header X-Powered-By; - -# Avoid clickjacking -add_header X-Frame-Options SAMEORIGIN; - -# Disable content-type sniffing on some browsers -add_header X-Content-Type-Options nosniff; - -# Enable the Cross-site scripting (XSS) filter -add_header X-XSS-Protection "1; mode=block"; - -# Disable directory listing -autoindex off; - -# Set cookies secure -#set_cookie_flag HttpOnly secure; - -# Enable CORS -add_header Access-Control-Allow-Origin '*'; - -# By removing the ETag header, you disable caches and browsers from being able to validate files, -# so they are forced to rely on your Cache-Control and Expires header. -# Basically you can remove If-Modified-Since and If-None-Match requests and their 304 Not Modified Responses. -etag off; \ No newline at end of file diff --git a/src/server/nginx/vhost-app.conf b/src/server/nginx/vhost-app.conf deleted file mode 100755 index 9e6f56d..0000000 --- a/src/server/nginx/vhost-app.conf +++ /dev/null @@ -1,6 +0,0 @@ -# @author Marcos Freitas - -# the following configuration snippet implements a 1‑second caching period for responses with a 200 OK status code. -fastcgi_cache_path /tmp/cache keys_zone=APPLICATION:10m levels=1:2 inactive=60m max_size=500m use_temp_path=off; - -include snippets/http-server.conf; \ No newline at end of file