상세 컨텐츠

본문 제목

web-was 구축해보기 (nginx-proxy) -(1)

web-application 시스템 구축

by drogva 2024. 4. 6. 23:47

본문

 

- web 역방향브록시서버-nginx 도커이미지 - was (rds 연결한 jar 파일) 도커이미지를 연결하기

-  eks 로 배포자동화 해보기.

 

- web 서버 nginx 역방향 프록시 설정하기

 아마존 리눅스에서 yum -y insall nginx 설치

 vi /etc/nginx/conf.d/defalut.conf   - 프록시 설정하기
 /etc/nginx/nginx.cof  와 합쳤다. 어차피 도커이미지로 빌드하기 때문에 한 파일로 합쳤다.

 

 

 

 

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    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;

    sendfile            on;
    tcp_nopush          on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    server {
        listen 8080;                                                         
        server_name web.seunghobet.link;                       

                # redirect https setting
  if ($http_x_forwarded_proto != 'https') {
    return 301 https://$host$request_uri;                
  }                                                                                                                                                                

        location / {
            root /usr/share/nginx/html;
            index index.html;
            try_files $uri $uri/ =404;
        }

        location /api/ {
            proxy_pass https://db.seunghobet.link;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location /api/super-shy {
            proxy_pass https://db.seunghobet.link;                                                         

            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}

 

 server {
        listen 8080;   
     
       ---->   eks service 에서 타겟포트 8080와 연결시키기 위해 맞춰줬다 
     
       server_name web.seunghobet.link;    

        ---> nginx 프록시 서버 주소 도메인



       

 

 

  # redirect https setting
  if ($http_x_forwarded_proto != 'https') {
    return 301 https://$host$request_uri;                 

}

 

 

----> 클라이언트가 http 로 접속하더라도 https 로 리다이렉트 되게 설정
       클라이언트가 http 접속상태로  /api/super-shy  경로를 통해 백앤드                                                                                     에  get 요청을 보내면 405 method not allowed 가 뜬다.

 

 

   location /api/super-shy {
            proxy_pass https://db.seunghobet.link;                                             

 

----> 프록시 서버의 url/super-shy 앤드포인트                                                                                                                                  로 접속하면 이동하게 될 was url           

 

 

config.js                 ----> 역방향 프록시 서버와 백앤드가 연결된 것을 확인하기 해 구성

 

document.addEventListener("DOMContentLoaded", function() {
    const superShyButton = document.getElementById("superShyButton");

    superShyButton.addEventListener("click", function() {
        fetchBackendData(); // 백엔드로의 요청을 보내는 함수 호출
    });
});

function fetchBackendData() {
    // 여기에 백엔드로 요청을 보내는 코드 작성
    const API_BASE_URL =  'https://web.seunghobet.link';
    const endpoint = '/api/super-shy'; // 클릭 시 요청할 엔드포인트를 변경

    fetch(API_BASE_URL + endpoint)
        .then(response => response.json())
        .then(data => {
            // 요청에 대한 처리
            console.log(data);
        })
        .catch(error => {
            // 오류 처리
            console.error('Error:', error);
        });
}

 

---: URL로 GET 요청을 보내고, 응답 데이터를 JSON 형식으로 파싱합니다. 성공적으로 응답을 받으면 데이터를 콘솔에 로깅 가능하다는 메시지 출력.

 

 

 

index.html 

 

에는 버튼클릭하면서  /api/super-shy 앤드포인트를 통해 백앤드 get 신호를 보낸다. 백앤드 리퀘스트를 처리하여 응답으로 반환. 반환메시지가 확인되면 백앤드로 이동.

 

<!-- JavaScript code -->
<script>
    document.getElementById("superShyButton").addEventListener("click", function() {
        // 클릭 시 백엔드로 요청을 보냅니다.
        fetch('https://web.seunghobet.link/api/super-shy') // 백엔드 프록시 경로로 변경
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 요청이 성공한 경우 새로운 URL로 이동합니다.
                window.location.href = "https://db.seunghobet.link"; // 백엔드 프록시 경로로 변경
            })
            .catch(error => {
                // 오류 처리
                console.error('Error:', error);
                // 요청이 실패하더라도 아무 작업도 수행하지 않습니다.
            });
    });
</script>
</body>
</html>

 

 

 

관련글 더보기