Skip to content

Commit

Permalink
新增 docker 支持
Browse files Browse the repository at this point in the history
1、增加 docker 支持,一条命令启动所有服务
  • Loading branch information
barats committed Apr 7, 2022
1 parent d2f504a commit 4909c63
Show file tree
Hide file tree
Showing 10 changed files with 167 additions and 46 deletions.
3 changes: 3 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.vscode
docker/container-data/*
tmp
19 changes: 19 additions & 0 deletions docker/admin.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
##
## Build
##
FROM golang:1.16-alpine AS ohurlshortener_builder
ENV GO111MODULE=on
ENV GOPROXY=https://proxy.golang.com.cn,direct
ADD . /app
WORKDIR /app
RUN go mod download && go build -o ohurlshortener .

##
## Deploy
##
FROM alpine:latest
WORKDIR /app
COPY --from=ohurlshortener_builder /app/ohurlshortener .
EXPOSE 9092
ENTRYPOINT ["/app/ohurlshortener","-s","admin","-c","config.ini"]

21 changes: 21 additions & 0 deletions docker/docker_config.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
[app]
debug = false
port = 9091
admin_port = 9092
url_prefix = http://localhost:9091/

[redis]
host = redis:6379
database = 0
username =
password =
pool_size = 50

[postgres]
host = postgres
port = 5432
user = postgres
password = 0DePm!oG_12Cz^kd_m
database = oh_url_shortener
max_open_conn = 20
max_idle_conn = 5
4 changes: 2 additions & 2 deletions docker/build_start.sh → docker/one_step_start.sh
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# !/bin/bash
docker-compose -p ohurlshortener -f services.yml --env-file vars.env up -d --build
#!/usr/bin/env bash
docker-compose -p ohurlshortener -f services.yml --env-file vars.env up -d --build --force-recreate
19 changes: 19 additions & 0 deletions docker/portal.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
##
## Build
##
FROM golang:1.16-alpine AS ohurlshortener_builder
ENV GO111MODULE=on
ENV GOPROXY=https://proxy.golang.com.cn,direct
ADD . /app
WORKDIR /app
RUN go mod download && go build -o ohurlshortener .

##
## Deploy
##
FROM alpine:latest
WORKDIR /app
COPY --from=ohurlshortener_builder /app/ohurlshortener .
EXPOSE 9091
ENTRYPOINT ["/app/ohurlshortener","-s","portal","-c","config.ini"]

58 changes: 51 additions & 7 deletions docker/services.yml
Original file line number Diff line number Diff line change
@@ -1,29 +1,73 @@
version: '3'
services:

ohurlshortener-admin:
image: ohurlshortener/admin:1.0
container_name: ${OH_ADMIN_CONTAINER_NAME}
hostname: oh_admin
build:
context: ../
dockerfile: docker/admin.Dockerfile
volumes:
- ../docker/docker_config.ini:/app/config.ini
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
ports:
- ${OH_ADMIN_PORT}:9092
networks:
- ohurlshortener

ohurlshortener-portal:
image: ohurlshortener/portal:1.0
container_name: ${OH_PORTAL_CONTAINER_NAME}
hostname: oh_portal
build:
context: ../
dockerfile: docker/portal.Dockerfile
volumes:
- ../docker/docker_config.ini:/app/config.ini
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
ports:
- ${OH_PORTAL_PORT}:9091
networks:
- ohurlshortener

postgres:
image: postgres:${PG_VERSION}
container_name: ${PG_CONTAINER_NAME}
hostname: postgres
environment:
- POSTGRES_USER=${PG_SUPER_USER}
- POSTGRES_PASSWORD=${PG_SUPER_PWD}
- POSTGRES_PASSWORD=${PG_SUPER_PWD}
- TZ=PRC
- PGTZ=PRC
volumes:
- ../structure.sql:/docker-entrypoint-initdb.d/001.sql
- ../docker/container-data/postgresql:/var/lib/postgresql/data
ports:
- ${PG_LOCAL_PORT}:5432
healthcheck:
test: [ "CMD", "psql", "-U","${PG_SUPER_USER}","-d","oh_url_shortener" ]
timeout: 10s
interval: 3s
retries: 10
networks:
- ohurlshortener
- ohurlshortener

redis:
image: redis:${RD_VERSION}
container_name: ${RD_CONTAINER_NAME}
hostname: redis
ports:
- ${RD_LOCAL_PORT}:6379
hostname: redis
healthcheck:
test: [ "CMD", "redis-cli","-p","6379"]
timeout: 10s
interval: 3s
retries: 10
networks:
- ohurlshortener

Expand Down
2 changes: 1 addition & 1 deletion docker/destory_stop.sh → docker/stop_destory.sh
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# !/bin/bash
#!/usr/bin/env bash
docker-compose -p ohurlshortener -f services.yml --env-file vars.env down
10 changes: 8 additions & 2 deletions docker/vars.env
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
# Environment Variables for docker-compose

# ohUrlShortenerAdmin
OH_ADMIN_PORT=9092
OH_ADMIN_CONTAINER_NAME=ohurlshortener_admin

# ohUrlShortenerPortal
OH_PORTAL_PORT=9091
OH_PORTAL_CONTAINER_NAME=ohurlshortener_portal

# Postgresql Vars
PG_VERSION=9.6
PG_CONTAINER_NAME=ohurlshortener_pg
PG_LOCAL_PORT=55432
PG_SUPER_USER=postgres
PG_SUPER_PWD=0DePm!oG_12Cz^kd_m

#Redis Vars
RD_VERSION=6.2.6
RD_CONTAINER_NAME=ohurlshortener_redis
RD_LOCAL_PORT=56379
71 changes: 40 additions & 31 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"ohurlshortener/service"
"ohurlshortener/storage"
"ohurlshortener/utils"
"os"
"strings"
"time"

Expand All @@ -41,28 +42,23 @@ var (

group errgroup.Group

cmdStart *string
cmdStart string
cmdConfig string
)

func init() {
//Things MUST BE DONE before app starts
_, err := utils.InitConfig(CONFIG_FILE)
utils.ExitOnError("Config initialization failed.", err)

_, err = storage.InitRedisService()
utils.ExitOnError("Redis initialization failed.", err)

_, err = storage.InitDatabaseService()
utils.ExitOnError("Database initialization failed.", err)
func main() {

_, err = service.ReloadUrls()
utils.PrintOnError("Realod urls failed.", err)
flag.StringVar(&cmdStart, "s", "", "starts ohurlshortener service: admin | portal ")
flag.StringVar(&cmdConfig, "c", "config.ini", "config file path")
flag.Usage = func() {
fmt.Fprintf(os.Stdout, `ohUrlShortener version:1.0
Usage: ohurlshortener [-s admin|portal|<omit to start both>] [-c config_file_path]`)
flag.PrintDefaults()
}

err = service.ReloadUsers()
utils.PrintOnError("Realod users failed.", err)
}
flag.Parse()

func main() {
initSettings()

router01, err := initializeRoute01()
utils.ExitOnError("Router01 initialize failed.", err)
Expand All @@ -71,54 +67,67 @@ func main() {
utils.ExitOnError("Router02 initialize failed.", err)

portal := &http.Server{
Addr: fmt.Sprintf("127.0.0.1:%d", utils.AppConfig.Port),
Addr: fmt.Sprintf(":%d", utils.AppConfig.Port),
Handler: router01,
ReadTimeout: WEB_READ_TIMEOUT,
WriteTimeout: WEB_WRITE_TIMEOUT,
}

admin := &http.Server{
Addr: fmt.Sprintf("127.0.0.1:%d", utils.AppConfig.AdminPort),
Addr: fmt.Sprintf(":%d", utils.AppConfig.AdminPort),
Handler: router02,
ReadTimeout: WEB_READ_TIMEOUT,
WriteTimeout: WEB_WRITE_TIMEOUT,
}

cmdStart = flag.String("start", "", "admin | portal | (omit to start both)")
flag.Parse()

if strings.EqualFold("admin", strings.ToLower(*cmdStart)) {
if strings.EqualFold("admin", strings.TrimSpace(cmdStart)) {
startAdmin(group, *admin)
}

if strings.EqualFold("portal", strings.ToLower(*cmdStart)) {
} else if strings.EqualFold("portal", strings.TrimSpace(cmdStart)) {
startPortal(group, *portal)
}

if utils.EemptyString(*cmdStart) {
} else if utils.EemptyString(cmdStart) {
startPortal(group, *portal)
startAdmin(group, *admin)
} else {
flag.Usage()
}

err = group.Wait()
utils.ExitOnError("Group failed,", err)
}

func initSettings() {
//Things MUST BE DONE before app starts
_, err := utils.InitConfig(cmdConfig)
utils.ExitOnError("Config initialization failed.", err)

_, err = storage.InitRedisService()
utils.ExitOnError("Redis initialization failed.", err)

_, err = storage.InitDatabaseService()
utils.ExitOnError("Database initialization failed.", err)

_, err = service.ReloadUrls()
utils.PrintOnError("Realod urls failed.", err)

err = service.ReloadUsers()
utils.PrintOnError("Realod users failed.", err)
}

func startPortal(g errgroup.Group, server http.Server) {
group.Go(func() error {
log.Println("[ohUrlShortener] ticker starts to serve")
return startTicker()
})

group.Go(func() error {
log.Printf("[ohUrlShortener] portal starts at http://127.0.0.1:%d", utils.AppConfig.Port)
log.Printf("[ohUrlShortener] portal starts at http://localhost:%d", utils.AppConfig.Port)
return server.ListenAndServe()
})
}

func startAdmin(g errgroup.Group, server http.Server) {
group.Go(func() error {
log.Printf("[ohUrlShortener] admin starts at http://127.0.0.1:%d", utils.AppConfig.AdminPort)
log.Printf("[ohUrlShortener] admin starts at http://localhost:%d", utils.AppConfig.AdminPort)
return server.ListenAndServe()
})
}
Expand Down
6 changes: 3 additions & 3 deletions structure.sql
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ CREATE TABLE public.short_urls (
);

INSERT INTO public.short_urls(short_url, dest_url, created_at, is_valid, memo)
VALUES('AC7VgPE9', 'https://www.gitlink.org.cn/baladiwei/ohurlshortener', '2022-04-01 17:31:41.270', true, '短链接系统 gitlink 页面');
VALUES('AC7VgPE9', 'https://www.gitlink.org.cn/baladiwei/ohurlshortener', NOW(), true, '短链接系统 gitlink 页面');

INSERT INTO public.short_urls(short_url, dest_url, created_at, is_valid, memo)
VALUES('AvTkHZP7', 'https://gitee.com/barat/ohurlshortener', '2022-04-01 17:31:55.899', true, '短链接系统 gitee 页面');
VALUES('AvTkHZP7', 'https://gitee.com/barat/ohurlshortener', NOW(), true, '短链接系统 gitee 页面');

INSERT INTO public.short_urls(short_url, dest_url, created_at, is_valid, memo)
VALUES('gkT39tb5', 'https://github.com/barats/ohUrlShortener', '2022-04-01 17:32:13.209', true, '短链接系统 github 页面');
VALUES('gkT39tb5', 'https://github.com/barats/ohUrlShortener', NOW(), true, '短链接系统 github 页面');


CREATE TABLE public.access_logs (
Expand Down

0 comments on commit 4909c63

Please sign in to comment.