Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

deploy(KL-184): 서버 배포 #71

Open
wants to merge 46 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
c4fb1a4
KL-184/feat: add config for prod
ohhamma Oct 8, 2024
c9db988
KL-184/refactor: apply options for each db and environment
ohhamma Oct 8, 2024
6ad37ef
KL-184/refactor: apply test config
ohhamma Oct 8, 2024
de6c89a
KL-184/feat: add data for prod
ohhamma Oct 8, 2024
596b10b
KL-184/refactor: apply data for each profile
ohhamma Oct 8, 2024
6920713
KL-184/refactor: add https in domain env
ohhamma Oct 8, 2024
5da1d11
KL-184/deploy: add workflow
ohhamma Oct 8, 2024
b4f3e3f
KL-184/deploy: use compose.yaml
ohhamma Oct 8, 2024
8846cbf
KL-184/deploy: apply makefile
ohhamma Oct 8, 2024
a90071f
KL-184/deploy: copy files to ec2
ohhamma Oct 9, 2024
e746532
KL-184/deploy: remove makefile usage
ohhamma Oct 9, 2024
fa162e1
KL-184/deploy: build with gradle
ohhamma Oct 9, 2024
a4a3622
KL-184/deploy: build with makefile
ohhamma Oct 9, 2024
a3d7029
KL-184/deploy: build without test
ohhamma Oct 9, 2024
b2737c0
KL-184/deploy: remove copy file code
ohhamma Oct 10, 2024
0e37a20
KL-184/chore: remove compose version
ohhamma Oct 10, 2024
1ba8f7d
KL-184/deploy: add docker login script in ec2
ohhamma Oct 10, 2024
19f7976
KL-184/deploy: copy files to ec2
ohhamma Oct 10, 2024
32b2fa0
KL-184/deploy: docker compose without build
ohhamma Oct 10, 2024
637bba3
KL-184/deploy: build with gradle
ohhamma Oct 10, 2024
45e5b96
KL-184/test: add active profile for tests
ohhamma Oct 10, 2024
a2cf34e
KL-184/deploy: minimize log for prod
ohhamma Oct 10, 2024
fc7a7fb
KL-184/deploy: add mysql volume
ohhamma Oct 10, 2024
81243f1
KL-184/deploy: add log for prod
ohhamma Oct 10, 2024
d02c486
kL-184/deploy: rename docker network
ohhamma Oct 10, 2024
a118df5
KL-184/deploy: prune docker image after compose
ohhamma Oct 10, 2024
1a372f2
KL-184/deploy: use makefile
ohhamma Oct 10, 2024
829f9df
KL-184/deploy: docker compose down before deploy
ohhamma Oct 10, 2024
c00d841
KL-184/deploy: remove build
ohhamma Oct 10, 2024
d5a016b
KL-184/chore: add default static html
ohhamma Oct 11, 2024
57814b9
KL-184/fix: permit both endpoints
ohhamma Oct 11, 2024
f8fc468
KL-184/chore: add temp favicon
ohhamma Oct 11, 2024
7093453
KL-184/refactor: change security config sequence
ohhamma Oct 11, 2024
34d14f4
KL-184/fix: add static endpoint in public
ohhamma Oct 11, 2024
8576de0
KL-184/fix: change authorize endpoint sequence
ohhamma Oct 11, 2024
d374f5d
KL-184/fix: handle public endpoint error
ohhamma Oct 11, 2024
425bef6
KL-184/fix: handle public token auth error
ohhamma Oct 11, 2024
58ddcef
KL-184/fix: change security authorization sequence
ohhamma Oct 11, 2024
fe00120
KL-184/refactor: add methods to simplify code
ohhamma Oct 11, 2024
cd4efb6
KL-184/fix: fix checkstyle errors
ohhamma Oct 11, 2024
1e40ee3
KL-184/fix: handle authentication error
ohhamma Oct 11, 2024
6662a22
KL-184/fix: handle token auth error
ohhamma Oct 11, 2024
57e4a67
KL-184/fix: handle token auth error
ohhamma Oct 11, 2024
3ac7bf6
KL-184/feat: add health check endpoint
ohhamma Oct 11, 2024
626f7bc
KL-184/chore: remove unnecessary endpoint
ohhamma Oct 11, 2024
f51cec2
KL-184/fix: fix checkstyle error
ohhamma Oct 11, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions .github/workflows/deploy.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
name: Build and Deploy using Docker Compose

on:
push:
branches: [ "main", "develop" ]
pull_request:
branches: [ "main", "develop" ]
workflow_dispatch:

jobs:
build-and-deploy:
runs-on: ubuntu-latest
environment: dev
strategy:
matrix:
java-version: [ 17 ]
distribution: [ "zulu" ]

steps:
- name: Checkout Repository
uses: actions/checkout@v4

- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java-version }}
distribution: ${{ matrix.distribution }}

- name: Set up Gradle
uses: gradle/actions/setup-gradle@v3
with:
gradle-version: 8.8

- name: Grant execute permission for gradlew
run: chmod +x ./gradlew

- name: Create .env file
run: |
touch .env
echo "${{ secrets.ENV }}" > .env
shell: bash

- name: Build with Gradle
run: ./gradlew clean build -x test

- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}

- name: Build and Push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
platforms: linux/amd64/v3
push: true
tags: ${{ secrets.DOCKER_USERNAME }}/${{ secrets.DOCKER_IMAGE_NAME }}:latest

- name: Copy files to EC2
uses: appleboy/scp-action@master
with:
host: ${{ secrets.EC2_HOST }}
username: ${{ secrets.EC2_USERNAME }}
key: ${{ secrets.EC2_KEY }}
source: "compose.yaml,.env"
target: "~"

- name: Deploy to EC2
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.EC2_HOST }}
username: ${{ secrets.EC2_USERNAME }}
key: ${{ secrets.EC2_KEY }}
script: |
cd ~
sudo docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }}
sudo docker pull ${{ secrets.DOCKER_USERNAME }}/${{ secrets.DOCKER_IMAGE_NAME }}:latest
sudo docker compose down
sudo docker system prune -af --volumes
sudo docker compose up -d
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ compile:

build:
@make clean
@./gradlew build
@./gradlew build -x test

test:
@./gradlew test
Expand Down
20 changes: 13 additions & 7 deletions compose.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
version: "3"
services:
spring:
build: .
image: ${DOCKER_USERNAME}/${DOCKER_IMAGE_NAME}:latest
ports:
- "8080:8080"
container_name: "klkl-server"
Expand All @@ -12,7 +11,7 @@ services:
condition: service_healthy
restart: always
networks:
- dev-net
- klkl-net

klkl_db:
image: mysql:8.0
Expand All @@ -21,13 +20,20 @@ services:
container_name: "klkl-db"
env_file:
- .env
volumes:
- mysql-data:/var/lib/mysql
healthcheck:
interval: 5s
test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "--password=${MYSQL_ROOT_PASSWORD}"]
interval: 10s
timeout: 5s
retries: 5
restart: always
networks:
- dev-net
- klkl-net

networks:
dev-net:
klkl-net:
driver: bridge

volumes:
mysql-data:
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ private List<SimpleGrantedAuthority> getAuthorities(final Claims claims) {

public boolean validateToken(final String token) {
if (!StringUtils.hasText(token)) {
return false;
throw new TokenInvalidException();
}
try {
Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Excepti
.requestMatchers(HttpMethod.PUT).hasAnyRole(USER.name(), ADMIN.name())
.requestMatchers(HttpMethod.DELETE).hasAnyRole(USER.name(), ADMIN.name())
.requestMatchers(getUserRoleEndpoints()).hasRole(USER.name())
.requestMatchers(getBothEndpoints()).permitAll()
.requestMatchers(getPublicEndpoints()).permitAll()
.anyRequest().authenticated()
)
Expand Down Expand Up @@ -127,6 +128,10 @@ private RequestMatcher[] getUserRoleEndpoints() {
return SecurityEndpoint.USER_ROLE.getMatchers();
}

private RequestMatcher[] getBothEndpoints() {
return SecurityEndpoint.BOTH.getMatchers();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import lombok.Getter;
import lombok.RequiredArgsConstructor;


@Getter
@RequiredArgsConstructor
public enum SecurityEndpoint {
Expand All @@ -19,6 +18,9 @@ public enum SecurityEndpoint {
new AntPathRequestMatcher("/error"),
new AntPathRequestMatcher("/favicon.ico"),

// health check
new AntPathRequestMatcher("/health"),

// swagger
new AntPathRequestMatcher("/swagger-ui/**"),
new AntPathRequestMatcher("/swagger-ui.html"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.io.IOException;

import org.springframework.http.HttpMethod;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
Expand Down Expand Up @@ -31,11 +32,8 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {

@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
if ("GET".equalsIgnoreCase(request.getMethod())) {
return SecurityEndpoint.isPublicEndpoint(request)
&& !SecurityEndpoint.isBothEndpoint(request);
}
return false;
return HttpMethod.GET.matches(request.getMethod())
&& SecurityEndpoint.isPublicEndpoint(request);
}

@Override
Expand All @@ -46,20 +44,20 @@ protected void doFilterInternal(
) throws ServletException, IOException {
final String accessToken = tokenUtil.resolveToken(request);

if (accessToken == null && SecurityEndpoint.isBothEndpoint(request)) {
proceedWithoutAuthentication(request, response, filterChain);
return;
if (!StringUtils.hasText(accessToken)) {
if (HttpMethod.GET.matches(request.getMethod()) && SecurityEndpoint.isBothEndpoint(request)) {
proceedWithoutAuthentication(request, response, filterChain);
return;
}
}

try {
if (tokenProvider.validateToken(accessToken)) {
setAuthentication(accessToken);
} else {
final String reissueAccessToken = tokenProvider.reissueAccessToken(accessToken);
if (StringUtils.hasText(reissueAccessToken)) {
setAuthentication(reissueAccessToken);
tokenUtil.addAccessTokenCookie(response, reissueAccessToken);
}
setAuthentication(reissueAccessToken);
tokenUtil.addAccessTokenCookie(response, reissueAccessToken);
}
} catch (TokenInvalidException | TokenExpiredException e) {
handleTokenException(request, response, filterChain, e);
Expand All @@ -73,6 +71,9 @@ protected void doFilterInternal(
}

private void setAuthentication(final String accessToken) {
if (!StringUtils.hasText(accessToken)) {
throw new TokenInvalidException();
}
Authentication authentication = tokenProvider.getAuthentication(accessToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
Expand All @@ -84,11 +85,7 @@ private void handleTokenException(
CustomException ex
) throws IOException, ServletException {
SecurityContextHolder.clearContext();
if (SecurityEndpoint.isBothEndpoint(request)) {
proceedWithoutAuthentication(request, response, filterChain);
} else {
responseUtil.sendErrorResponse(response, ex);
}
responseUtil.sendErrorResponse(response, ex);
}

private void proceedWithoutAuthentication(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package taco.klkl.global.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HealthCheckController {

@GetMapping("/health")
public ResponseEntity<String> healthCheck() {
return ResponseEntity.ok("OK");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ private void init() {
}

public static String generateUrlByFileName(final String fileName) {
return "https://" + cloudFrontDomain + "/" + fileName;
return cloudFrontDomain + "/" + fileName;
}
}
27 changes: 25 additions & 2 deletions src/main/resources/application-dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,29 @@ spring:
config:
activate:
on-profile: "dev"
jpa:
hibernate:
ddl-auto: update
properties:
hibernate:
show_sql: true
format_sql: true
jdbc:
time_zone: ${TZ}
defer-datasource-initialization: true
sql:
init:
mode: always
data-locations: classpath:sql/data-dev.sql

api:
main-url: ${DEV_URL}
logging:
level:
root: INFO
taco.klkl: DEBUG
org.springframework: INFO
org.hibernate.SQL: DEBUG
org.hibernate.type.descriptor.sql: DEBUG

pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} - %msg%n"
file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
19 changes: 2 additions & 17 deletions src/main/resources/application-h2.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,16 @@ spring:
config:
activate:
on-profile: "h2"
jpa:
show-sql: true
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create
defer-datasource-initialization: true
properties:
hibernate:
show_sql: true
format_sql: true
jdbc:
time_zone: ${TZ}
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:klkldb;MODE=MySQL
username: sa
password:
jpa:
database-platform: org.hibernate.dialect.H2Dialect
h2:
console:
enabled: true
path: /h2-console
settings:
web-allow-others: true
sql:
init:
data-locations: classpath:database/data-h2.sql
mode: always
platform: h2
18 changes: 13 additions & 5 deletions src/main/resources/application-local.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,28 @@ spring:
activate:
on-profile: "local"
jpa:
hibernate:
ddl-auto: create
properties:
hibernate:
show_sql: true
format_sql: true

api:
main-url: ${LOCAL_URL}
jdbc:
time_zone: ${TZ}
defer-datasource-initialization: true
sql:
init:
mode: always
data-locations: classpath:sql/data-local.sql
platform: h2

logging:
level:
root: INFO
org.springframework.web: DEBUG
taco.klkl: DEBUG
org.springframework: DEBUG
org.hibernate.SQL: DEBUG
org.hibernate.type.descriptor.sql.BasicBinder: TRACE
org.hibernate.type.descriptor.sql: TRACE

pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} - %msg%n"
Expand Down
11 changes: 0 additions & 11 deletions src/main/resources/application-mysql.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,4 @@ spring:
username: ${MYSQL_USER}
password: ${MYSQL_PASSWORD}
jpa:
hibernate:
ddl-auto: update
defer-datasource-initialization: true
properties:
hibernate:
show_sql: true
format_sql: true
database-platform: org.hibernate.dialect.MySQLDialect
sql:
init:
data-locations: classpath:database/data-mysql.sql
mode: always
Loading