【问题标题】:How do I run my main.go file without having to run them separately outside of the containers?如何运行我的 main.go 文件而不必在容器之外单独运行它们?
【发布时间】:2022-01-03 17:58:07
【问题描述】:

我有一个main.go 文件,用于运行一个应用程序,该应用程序启动一个服务器,该服务器公开一个端口,我可以从中运行端点。我试图将它 dockerise 并尽可能制作容纳应用程序和数据库的工作容器,但在运行 docker-compose up -d 之后我似乎仍然必须运行 go run main.go

// present folder structure
.
├── cities.json // holds records of all city names
├── docker-compose.yaml 
├── dockerfile
├── go.mod
├── go.sum
├── localmon.sh // bash script that does a mongoimport to import all records from cities.json into the db
├── main.go
└── README.md

有人告诉我,我可能必须映射一个卷,知道它的位置并让它执行。另一种选择(更复杂)是 bash 脚本(或两者兼而有之?)

我有点不确定如何去做,或者我现在应该如何处理我的 compose 文件和 dockerfile。

version: '3.3'
services:
  db:
    hostname: mongo-test
    container_name: "mongo-test"
    image: mongo
    networks:
      - app_test
    ports: 
        - "8001:27017" 
    #   - "27017:27017"
    env_file: .env
    restart: unless-stopped
    volumes:
      - ".mongodata:/data/db"
  
  app: 
    hostname: app-test
    container_name: "app"
    build: 
      context: .
      dockerfile: dockerfile
    networks:
      - app_test
    ports: 
      - "54321:8080"
      # - "8080:8080"
    restart: unless-stopped
    env_file: .env

networks:
  app_test: {}
FROM golang:1.17.5-alpine3.15

RUN mkdir /app
ADD . /app
WORKDIR /app

# Copies and downloads necessary dependencies
COPY go.mod ./
COPY go.sum ./
RUN go mod download
RUN go build -o main .

# Port 8080 exposed for use
EXPOSE 8080

# Command that starts the container
CMD ["./main"]
env file that holds some DB related stuff for the main.go file to use.

DB_URI=mongodb://mongo-test:8001
CITY_DB=nht_cities
COL_USER=user
COL_CITY=city
USER_AUTH_TOKEN=50dba...
// localmon.sh

#! /bin/bash
mongoimport --host 192.168.0.101  --port 8001 --db nht_cities --collection city --type json --file ./cities.json 

docker-compose logs 在运行最近的docker-compose up -d 之后

Attaching to mongo-test, app
app    | time="2022-01-03T20:08:52Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:09:02Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:09:13Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:09:24Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:09:34Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:09:45Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:09:55Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:10:06Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:10:17Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:10:27Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:10:38Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:10:48Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:10:59Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
... goes on for a bit

mongo-test | {"t":{"$date":"2022-01-03T20:08:42.360+00:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"-","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.362+00:00"},"s":"I",  "c":"NETWORK",  "id":4915701, "ctx":"main","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":13},"outgoing":{"minWireVersion":0,"maxWireVersion":13},"isInternalClient":true}}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.362+00:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.362+00:00"},"s":"I",  "c":"NETWORK",  "id":4648601, "ctx":"main","msg":"Implicit TCP FastOpen unavailable. If TCP FastOpen is required, set tcpFastOpenServer, tcpFastOpenClient, and tcpFastOpenQueueSize."}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.363+00:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.363+00:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationDonorService","ns":"config.tenantMigrationDonors"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.363+00:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationRecipientService","ns":"config.tenantMigrationRecipients"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.363+00:00"},"s":"I",  "c":"CONTROL",  "id":5945603, "ctx":"main","msg":"Multi threading initialized"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.364+00:00"},"s":"I",  "c":"CONTROL",  "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":1,"port":27017,"dbPath":"/data/db","architecture":"64-bit","host":"mongo-test"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.364+00:00"},"s":"I",  "c":"CONTROL",  "id":23403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"5.0.5","gitVersion":"d65fd89df3fc039b5c55933c0f71d647a54510ae","openSSLVersion":"OpenSSL 1.1.1f  31 Mar 2020","modules":[],"allocator":"tcmalloc","environment":{"distmod":"ubuntu2004","distarch":"x86_64","target_arch":"x86_64"}}}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.364+00:00"},"s":"I",  "c":"CONTROL",  "id":51765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Ubuntu","version":"20.04"}}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.364+00:00"},"s":"I",  "c":"CONTROL",  "id":21951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{"net":{"bindIp":"*"}}}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.365+00:00"},"s":"I",  "c":"STORAGE",  "id":22270,   "ctx":"initandlisten","msg":"Storage engine to use detected by data files","attr":{"dbpath":"/data/db","storageEngine":"wiredTiger"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.365+00:00"},"s":"I",  "c":"STORAGE",  "id":22297,   "ctx":"initandlisten","msg":"Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem","tags":["startupWarnings"]}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.365+00:00"},"s":"I",  "c":"STORAGE",  "id":22315,   "ctx":"initandlisten","msg":"Opening WiredTiger","attr":{"config":"create,cache_size=7178M,session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),builtin_extension_config=(zstd=(compression_level=6)),file_manager=(close_idle_time=600,close_scan_interval=10,close_handle_minimum=250),statistics_log=(wait=0),verbose=[recovery_progress,checkpoint_progress,compact_progress],"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.942+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240522:942716][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_PROGRESS] Recovering log 9 through 10"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.968+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240522:968493][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_PROGRESS] Recovering log 10 through 10"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.010+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240523:10614][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_ALL] Main recovery loop: starting at 9/5120 to 10/256"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.056+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240523:56865][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_PROGRESS] Recovering log 9 through 10"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.084+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240523:84544][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_PROGRESS] Recovering log 10 through 10"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.108+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240523:108553][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_ALL] Set global recovery timestamp: (0, 0)"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.108+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240523:108603][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_ALL] Set global oldest timestamp: (0, 0)"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.110+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240523:110204][1:0x7f62a3693c80], WT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 1, snapshot max: 1 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 616"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.115+00:00"},"s":"I",  "c":"STORAGE",  "id":4795906, "ctx":"initandlisten","msg":"WiredTiger opened","attr":{"durationMillis":750}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.115+00:00"},"s":"I",  "c":"RECOVERY", "id":23987,   "ctx":"initandlisten","msg":"WiredTiger recoveryTimestamp","attr":{"recoveryTimestamp":{"$timestamp":{"t":0,"i":0}}}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.116+00:00"},"s":"I",  "c":"STORAGE",  "id":4366408, "ctx":"initandlisten","msg":"No table logging settings modifications are required for existing WiredTiger tables","attr":{"loggingEnabled":true}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.117+00:00"},"s":"I",  "c":"STORAGE",  "id":22262,   "ctx":"initandlisten","msg":"Timestamp monitor starting"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.120+00:00"},"s":"W",  "c":"CONTROL",  "id":22120,   "ctx":"initandlisten","msg":"Access control is not enabled for the database. Read and write access to data and configuration is unrestricted","tags":["startupWarnings"]}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.123+00:00"},"s":"I",  "c":"NETWORK",  "id":4915702, "ctx":"initandlisten","msg":"Updated wire specification","attr":{"oldSpec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":13},"outgoing":{"minWireVersion":0,"maxWireVersion":13},"isInternalClient":true},"newSpec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInternalClient":{"minWireVersion":13,"maxWireVersion":13},"outgoing":{"minWireVersion":13,"maxWireVersion":13},"isInternalClient":true}}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.123+00:00"},"s":"I",  "c":"STORAGE",  "id":5071100, "ctx":"initandlisten","msg":"Clearing temp directory"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.123+00:00"},"s":"I",  "c":"CONTROL",  "id":20536,   "ctx":"initandlisten","msg":"Flow Control is enabled on this deployment"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.124+00:00"},"s":"I",  "c":"FTDC",     "id":20625,   "ctx":"initandlisten","msg":"Initializing full-time diagnostic data capture","attr":{"dataDirectory":"/data/db/diagnostic.data"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.126+00:00"},"s":"I",  "c":"REPL",     "id":6015317, "ctx":"initandlisten","msg":"Setting new configuration state","attr":{"newState":"ConfigReplicationDisabled","oldState":"ConfigPreStart"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.126+00:00"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"/tmp/mongodb-27017.sock"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.127+00:00"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"0.0.0.0"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.127+00:00"},"s":"I",  "c":"NETWORK",  "id":23016,   "ctx":"listener","msg":"Waiting for connections","attr":{"port":27017,"ssl":"off"}}
mongo-test | {"t":{"$date":"2022-01-03T20:09:43.122+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"Checkpointer","msg":"WiredTiger message","attr":{"message":"[1641240583:122644][1:0x7f629ae81700], WT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 3, snapshot max: 3 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 616"}}
mongo-test | {"t":{"$date":"2022-01-03T20:10:43.134+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"Checkpointer","msg":"WiredTiger message","attr":{"message":"[1641240643:134518][1:0x7f629ae81700], WT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 6, snapshot max: 6 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 616"}}
mongo-test | {"t":{"$date":"2022-01-03T20:11:43.147+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"Checkpointer","msg":"WiredTiger message","attr":{"message":"[1641240703:147808][1:0x7f629ae81700], WT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 8, snapshot max: 8 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 616"}}
package main

import (
    "context"
    "crypto/sha256"
    "encoding/json"
    "fmt"
    "math/rand"
    "net/http"
    "os"
    "time"

    "github.com/gorilla/mux"
    "github.com/joho/godotenv"
    log "github.com/sirupsen/logrus"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/readpref"
)

var client mongo.Client                                                                       // mongo client from setup declared globally
var characterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") // character runes used for creation of tokens

func setup() { // Setup for mongodb connection using mongo drivers. Returns client.
    clientOptions := options.Client().
        ApplyURI(os.Getenv("DB_URI"))
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    clientLocal, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        log.Fatalln(err, "This is from the first one")
    }
    err = clientLocal.Ping(ctx, readpref.Primary())
    if err != nil {
        log.Fatalln(err, "This is from the second one")
    }
    fmt.Println("MongoDB started successfully!")
    client = *clientLocal
}

// model for user endpoint
type User struct {
    Email       string `json:"email"`
    AccessToken string `json:"token"`
}

type City struct {
    Name string `bson:"name" json:"name"`
}

func main() {
    err := godotenv.Load() // Loads environment variables from .env
    if err != nil {
        log.Fatal("Error loading .env file")
    }

    setup()
    r := mux.NewRouter()
    r.Handle("/user", UserAuth(createUser)).Methods("POST")  // Route for registering new users
    r.Handle("/suggest", APIAuth(searchCity)).Methods("GET") // Route for searching cities within DB

    fmt.Println("Server running at port 8080")
    log.Fatal(http.ListenAndServe(":8080", r))

}

func createUser(w http.ResponseWriter, r *http.Request) { // POST request that takes in user details, generates an access token and inserts them into the DB
    w.Header().Add("content-type", "application/json")

    var user User
    _ = json.NewDecoder(r.Body).Decode(&user)
    userCollection := client.Database(os.Getenv("CITY_DB")).Collection(os.Getenv("COL_USER")) // Holds 'user' collection from DB
    user.AccessToken = generateToken()                                                        // Generated access token is assigned to user struct

    _, err := userCollection.InsertOne(context.Background(), user) // Details are inserted into the collection
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        log.Fatalln(err, "Failed to create user.")
    }
    json.NewEncoder(w).Encode(user)

}

func searchCity(w http.ResponseWriter, r *http.Request) { // GET request that takes in a url param and returns a list of cities from the DB
    w.Header().Set("Content-Type", "application/json")

    values := r.URL.Query()
    city := values["city_name"]                                                               // Assigns url param from route `/suggest?city_name=` to 'city'
    cityCollection := client.Database(os.Getenv("CITY_DB")).Collection(os.Getenv("COL_CITY")) // Holds 'city' collection from DB

    if len(city) == 0 {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte(`{"Error": "City name cannot be empty!"}`))
        return
    }

    filter := bson.D{ //Regex filter for querying the input through the DB
        primitive.E{
            Key: "all_names", Value: primitive.Regex{
                Pattern: city[0], Options: "i",
            },
        },
    }

    cursor, err := cityCollection.Find(r.Context(), filter) // Query to find city is declared with cursor
    if err != nil {
        log.Fatal(err)
        w.WriteHeader(http.StatusInternalServerError)
        w.Write([]byte(`{"Error": "Could not execute cursor into query."}`))
        return
    }

    var cityList []City
    for cursor.Next(context.TODO()) { // Runs through each document entry in DB to see if regex matches
        var cities City
        err := cursor.Decode(&cities)
        if err != nil {
            log.Fatal(err)
            w.WriteHeader(http.StatusInternalServerError)
            w.Write([]byte(`{"Error": "Could not run cursor."}`))
            return
        }
        cityList = append(cityList, cities) // List of cities is appended to cityList
    }
    w.WriteHeader(http.StatusOK)
    if len(cityList) == 0 {
        w.Write([]byte(`{"cities": []}`))
        return
    }
    json.NewEncoder(w).Encode(cityList)

}

func init() {
    rand.Seed(time.Now().UnixNano()) // Creates a new seed for randomising the access token
}

func genString(n int) string { // Generates a randomised string from the character runes
    b := make([]rune, n)
    for i := range b {
        b[i] = characterRunes[rand.Intn(len(characterRunes))]
    }
    return string(b)
}

func generateToken(n ...int) string { // Generates a token for when a new user registers their details
    characters := 32

    if len(n) > 0 {
        characters = n[0]
    }

    randString := genString(characters)

    h := sha256.New()
    h.Write([]byte(randString))
    generatedToken := h.Sum(nil)

    return fmt.Sprintf("%x", generatedToken)

}

func APIAuth(endpoint func(http.ResponseWriter, *http.Request)) http.Handler { // Middleware to check if access token is contained within header when running searchCity
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        accessToken := r.Header.Get("x-api-key")

        // Checks token in db
        usersCollection := client.Database(os.Getenv("CITY_DB")).Collection(os.Getenv("COL_USER"))
        filter := bson.D{
            primitive.E{
                Key: "accesstoken", Value: accessToken,
            },
        }

        var user User
        err := usersCollection.FindOne(context.TODO(), filter).Decode(&user)
        if err != nil {
            http.Error(w, `Unauthorized access`, http.StatusUnauthorized)
        } else if len(accessToken) == 0 {
            http.Error(w, `Unauthorized access`, http.StatusUnauthorized)
        } else {
            endpoint(w, r)
        }
    })
}

func UserAuth(endpoint func(http.ResponseWriter, *http.Request)) http.Handler { // Middleware to check if user registering has appropriate auth token
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        accessToken := r.Header.Get("x-access-token")
        if len(accessToken) == 0 {
            http.Error(w, "Unauthorized access, no token", http.StatusUnauthorized)
            return
        }

        if accessToken != os.Getenv("USER_AUTH_TOKEN") {
            http.Error(w, "Unauthorized access", http.StatusUnauthorized)
            return
        }

        endpoint(w, r)
    })
}

netstat -tulpn 正在运行容器

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      -                   
tcp        0      0 192.168.0.101:40571     0.0.0.0:*               LISTEN      3086/rygel          
tcp        0      0 127.0.0.1:5054          0.0.0.0:*               LISTEN      2967/python3        
tcp        0      0 172.17.0.1:41599        0.0.0.0:*               LISTEN      3086/rygel          
tcp        0      0 127.0.0.1:46624         0.0.0.0:*               LISTEN      2358/kited          
tcp        0      0 0.0.0.0:8001            0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.1:34179         0.0.0.0:*               LISTEN      3086/rygel          
tcp        0      0 172.23.0.1:39273        0.0.0.0:*               LISTEN      3086/rygel          
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      -                   
tcp        0      0 0.0.0.0:54321           0.0.0.0:*               LISTEN      -                   
tcp6       0      0 ::1:631                 :::*                    LISTEN      -                   
tcp6       0      0 :::8001                 :::*                    LISTEN      -                   
tcp6       0      0 :::5900                 :::*                    LISTEN      3083/gnome-remote-d 
tcp6       0      0 :::54321                :::*                    LISTEN      -                   
udp        0      0 127.0.0.53:53           0.0.0.0:*                           -                   
udp        0      0 172.17.0.1:41320        0.0.0.0:*                           3086/rygel          
udp        0      0 0.0.0.0:631             0.0.0.0:*                           -                   
udp        0      0 0.0.0.0:50334           0.0.0.0:*                           -                   
udp        0      0 239.255.255.250:1900    0.0.0.0:*                           3086/rygel          
udp        0      0 172.17.0.1:1900         0.0.0.0:*                           3086/rygel          
udp        0      0 239.255.255.250:1900    0.0.0.0:*                           3086/rygel          
udp        0      0 172.23.0.1:1900         0.0.0.0:*                           3086/rygel          
udp        0      0 239.255.255.250:1900    0.0.0.0:*                           3086/rygel          
udp        0      0 192.168.0.101:1900      0.0.0.0:*                           3086/rygel          
udp        0      0 239.255.255.250:1900    0.0.0.0:*                           3086/rygel          
udp        0      0 127.0.0.1:1900          0.0.0.0:*                           3086/rygel          
udp        0      0 127.0.0.1:52502         0.0.0.0:*                           3086/rygel          
udp        0      0 172.23.0.1:45184        0.0.0.0:*                           3086/rygel          
udp        0      0 192.168.0.101:53552     0.0.0.0:*                           3086/rygel          
udp        0      0 0.0.0.0:5353            0.0.0.0:*                           -                   
udp6       0      0 :::42415                :::*                                -                   
udp6       0      0 :::5353                 :::*                                -                   

【问题讨论】:

  • 嗨 Lazlo,恐怕我不明白问题出在哪里。能否请您说出您想做的事情以及不符合您预期的事情?
  • 为什么要在容器外运行 main.go?您使用哪个命令来启动您的应用程序的容器?
  • 嗨,安德烈。我要做的是运行docker compose up -d 并启动容器。这会从 compose 文件中启动应用程序和 mongo-test db。之后,我运行go run main.go 以使应用程序正常工作,但事实并非如此。我希望该部分已经由容器处理,而不是我必须手动处理。基本上,我希望main.go 文件作为docker-compose up -d 命令的一部分运行。希望这更有意义。
  • 在容器外运行应用程序违背了创建容器的目的。这不是一种解决方法:) 您在您的dockfefile 中正确指定了 CMD ["./main"]。您的应用程序似乎在启动时崩溃(无法连接到数据库?)。请使用“docker-compose logs ”命令查看日志。
  • 另一个问题:如何测试您的应用是否已启动?

标签: mongodb docker go


【解决方案1】:

请更改.env 文件中的以下行:

DB_URI=mongodb://mongo-test:8001

DB_URI=mongodb://mongo-test:27017

当您使用docker compose up 命令启动它们时,这些容器在同一个容器网络中运行。这意味着您需要指定容器端口而不是主机端口。容器端口在 Docker 王国中始终排在第二位:<host port>:<container port>

【讨论】:

  • 啊,有一个问题是 mongo 实例直接在主机上运行,​​不是在容器中。这就是我坚持使用 8001 的原因。我可以编辑 netstat -tulpn 登录以显示给您。
  • @Lazlo,docker-compose.yaml 明确指示 Docker 在 Docker 容器中启动 mongo。是什么让你认为它不起作用。真的很混乱。
  • 请尝试遵循答案中的建议,如果可行,请告诉我。
  • 我很抱歉,在重新阅读您多次说过的内容后,我想我明白了,您所说的确实有效。由于某种原因,我的大脑无法跟上,可能是因为我累了,现在快凌晨 3 点了。现在已经有一段时间了。我的端点网址现在位于http://localhost:54321。仍在尝试弄清楚如何从 cities.json 导入记录,因为我不确定在 .sh 文件中再使用哪个主机和端口。
  • 完全不用担心。有很多东西要处理。祝你一切顺利:)
猜你喜欢
  • 2021-07-26
  • 1970-01-01
  • 1970-01-01
  • 2015-10-17
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-26
相关资源
最近更新 更多