Dedicated Game Server Hosting

In this post, I’ll show you how to deploy a multiplayer game to the cloud. If you only want the tutorial, skip to the hands-on section. Otherwise, here’s some background first.

Understanding Dedicated Game Servers

When I started working on games, dedicated game servers were one of the hardest concepts for me to grasp as a backend engineer. Part of the confusion was the word “server.” Gameplay engineers used it to mean the dedicated game server, while in my career “the server” had always meant the backend.

In game development, they’re two different things. The backend is the platform that runs the online services a multiplayer game needs, like authentication, accounts, leaderboards and matchmaking. A dedicated game server is the authority on the game state: clients send it their actions, it updates the state, and it sends the latest state back so each client can draw it on screen.

Sequence diagram: the client sends an action and the server returns the new state

As a backend engineer on a new multiplayer game, you’re often the one orchestrating these servers. Services like matchmaking talk to them to host matches. A dedicated server is a headless process, written either in the game’s engine or in a separate language like Go or Node.js, and built to handle many player connections at once.

Understanding the concept is one thing. Putting it into practice is harder, and that’s what this post covers. I’ve tried to keep it beginner-friendly.

Game Server Hosting Solutions

If you search for game server hosting, you’ll find companies using one of three approaches.

Build Your Own Orchestrator

Some studios build their own game server orchestrator, either on their own hardware with software like OpenStack or on basic compute from a cloud provider, like EC2 on AWS or Compute Engine on Google Cloud. The orchestrator sits in the middle and allocates CPU and memory, scaling vertically or horizontally to manage the fleet of game servers.

You mostly see this with AAA games, the informal label for games with the biggest development and marketing budgets.

Use a Third-Party Service

This approach felt the most familiar to me. In web development, you pay for compute, on demand or upfront, and get a fully managed service in return. Game server hosting can work the same way.

You upload your game server builds through an API, allocate resources, and start servers as you need them. Most of these services also give you a dashboard to manage everything.

Multiplay, i3D.net, Edgegap, Hathora and Amazon GameLift are some of the big names. Most of my experience is with services like these, but I won’t recommend one here. Each differs in performance, pricing, scaling and developer experience, so it’s worth trying them yourself.

Use an Open Source Tool (This Tutorial)

Open source is free to start with, you can contribute to the tools you use, and the projects often have active communities behind them.

For game servers, the open source tool that stands out is Agones. It’s popular and battle-tested, and it describes itself as “a dedicated game server scaling and orchestration platform that runs on Kubernetes.” In this post, I’ll use Agones to host a multiplayer game.

Hands-On

Requirements

Before we can run anything on Agones, we need a game. Sticking with open source, we’ll use Godot. I’m using a simple game made by FinePointCGI (opens in new tab), who I think is one of the best creators of Godot and multiplayer tutorials out there.

Two-player Godot game on a side-scrolling rooftop level

As you can see, it’s a simple two-player game. This post is about hosting, so I won’t go into the gameplay. Once connected, each player controls a character and can fire a gun, and every action is synced across both screens.

I forked the project and made one change: instead of one player acting as the server, both players now connect to a remote server running on Agones.

You can find the repository at github.com/andresromerodev/godot-agones-multiplayer (opens in new tab). Download it and open it in Godot.

Game lobby with IP and port fields

If you only have one computer, you’ll need to run two game clients at the same time. Open the project and go to Debug → Run Multiple Instances → Run 2 instances.

I won’t cover gameplay or networking here. If you want to learn about them, I recommend this video tutorial: youtube.com/watch/e0JLO_5UgQo (opens in new tab).

There are three parts of the code related to Agones that are worth explaining, though. When you host game servers, you need to keep track of the running instances: their IP and port, whether they’re healthy, and whether they’re ready to accept players. Agones does this through an SDK. Here we’ll use the community Agones SDK for Godot: github.com/AndreMicheletti/godot-agones-sdk (opens in new tab).

Setting it up is simple, and we only need three functions: start(), ready() and health().

Starting the Agones SDK

Start the SDK as early as possible so it’s ready before any other SDK call. In Godot, the best place is the _ready() function, which runs when the game server process starts.

func _ready():
	AgonesSDK.start()
	if "--server" in OS.get_cmdline_args():
		hostGame()

Reporting the Game Server as Ready

Once the SDK has started and your game has finished setting up, the last step is to report the server as “ready.” This tells Agones that players can now join. I do this in a hostGame() function in the MultiplayerController.gd script, which reports the server as ready once it’s listening on its port.

func hostGame():
	peer = ENetMultiplayerPeer.new()
	var error = peer.create_server(server_port, 2)

	if error != OK:
		print("cannot host: " + error)
		return

	peer.get_host().compress(ENetConnection.COMPRESS_ZLIB)
	multiplayer.set_multiplayer_peer(peer)

	AgonesSDK.ready()

	print("Reported game server as ready to Agones...")
	print("Waiting For Players!")

Reporting the Game Server as Healthy

To manage game servers at scale, each one has to report its health regularly with the SDK’s health() function. Since this needs to keep happening for as long as the server runs, I put it in Godot’s _process() function, which runs every frame, and send a health report every 60 seconds.

var elapsed_time = 0.0  # Time since the last health report

# Called every frame. 'delta' is the time since the previous frame.
func _process(delta):
	if peer:
		elapsed_time += delta

		if elapsed_time >= 60.0:  # Report health every 60 seconds
			AgonesSDK.health()
			elapsed_time = 0.0

Now let’s set up Agones and Kubernetes.

Running Agones

To keep things simple, I’m using DigitalOcean as the infrastructure provider. Its managed Kubernetes service makes it easy to create clusters and nodes.

If you’re new to Kubernetes, start with this guide (opens in new tab). It explains Kubernetes in simple terms and covers enough for what we’ll do here.

Let’s create a cluster in DigitalOcean. New accounts get $200 in credit, which is more than enough for this tutorial.

  1. Go to the Kubernetes section and click “Create.” Most of the defaults are fine, but make sure the node has at least 4 GB of RAM and 2 vCPUs. One node is enough for this example.

    DigitalOcean node pool: 1 node with 4 GB RAM and 2 vCPUs
  2. The cluster takes 2 to 4 minutes to start. When it’s ready, you’ll see it running.

    DigitalOcean cluster overview with 1/1 nodes running
  3. In the cluster dashboard, click Actions → Download Config and save the file somewhere you’ll remember, for example as digital-ocean.yaml.

  4. Open a terminal and set the KUBECONFIG environment variable to the path of that file.

    # Windows (Command Prompt)
    set KUBECONFIG=C:\path\to\your\kubeconfig.yaml
    # Linux/macOS
    export KUBECONFIG=/path/to/your/kubeconfig.yaml
  5. In the same terminal, check that you’re connected to the cluster:

    $ kubectl get nodes
    NAME                   STATUS   ROLES    AGE   VERSION
    pool-3a573me0i-bnc3y   Ready    <none>   63m   v1.30.2
  6. Install Agones with Helm:

    helm repo add agones https://agones.dev/chart/stable
    helm repo update
    helm install agones-release --namespace agones-system --create-namespace agones/agones
  7. Wait until all the Agones pods are running:

    $ kubectl get pods -A
    NAMESPACE       NAME                                 READY   STATUS    RESTARTS   AGE
    agones-system   agones-allocator-75cb8cbc79-6jw7c    1/1     Running   0          1m
    agones-system   agones-controller-69bd4676f7-cmrrd   1/1     Running   0          1m
    agones-system   agones-extensions-666d6f4666-pd4hc   1/1     Running   0          1m
    agones-system   agones-ping-7786b574cd-68q6c         1/1     Running   0          1m
  8. Finally, open the cluster firewall so players can reach your game servers over UDP. Go to Networking → Firewalls and select the cluster’s non-public firewall. Under “Inbound Rules,” add an “All UDP” rule that allows all IPv4 and IPv6 sources.

    Firewall inbound rules with an All UDP rule added

That’s it: the cluster is set up and running Agones.

Building the Game Server

We have a game and a cluster. To run the game on the cluster, we’ll package the game server as a Docker image, since that’s what Kubernetes runs.

The repo includes a Dockerfile that uses CentOS as its base image.

FROM centos:latest
WORKDIR /etc/yum.repos.d/

# Update repository URLs
RUN sed -i 's/mirrorlist/#mirrorlist/g' CentOS-* && sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' CentOS-*

# Install necessary packages
RUN dnf install -y curl unzip libXcursor openssl openssl-libs libXinerama libXrandr-devel libXi alsa-lib pulseaudio-libs mesa-libGL && dnf clean all

# Set Godot version as an environment variable
ENV GODOT_VERSION="4.2.2"

# Download Godot from GitHub
RUN curl -LO https://github.com/godotengine/godot/releases/download/${GODOT_VERSION}-stable/Godot_v${GODOT_VERSION}-stable_linux.x86_64.zip

# Unzip and move the Godot binary to the appropriate directory
RUN unzip Godot_v${GODOT_VERSION}-stable_linux.x86_64.zip
RUN mv Godot_v${GODOT_VERSION}-stable_linux.x86_64 /usr/local/bin/godot

# Make the Godot binary executable
RUN chmod +x /usr/local/bin/godot

# Clean up the zip file
RUN rm Godot_v${GODOT_VERSION}-stable_linux.x86_64.zip

# Update system and install ca-certificates
RUN dnf -y update && dnf -y install ca-certificates && update-ca-trust && dnf clean all

EXPOSE 8910

COPY game.pck .

CMD ["/usr/local/bin/godot", "--headless", "--main-pack", "./game.pck", "--server"]

It installs Godot and runs game.pck, which is the dedicated game server. I included the .pck in the repo. The Dockerfile could be better here: ideally it would build the .pck itself instead of relying on a manual export. For now, if you change the project, re-export the server in Godot from Project → Export → Linux → Export PCK/ZIP.

Once you have the updated .pck, build the Docker image:

docker build --pull --rm -f "dockerfile" -t godotagonesmultiplayer:latest "."

Pushing the Image to a Public Registry

Kubernetes needs to pull the image from somewhere. To keep things simple, we’ll use a public repository on Docker Hub (opens in new tab). Mine is called godotagonesmultiplayer, and you can find it here (opens in new tab).

For this tutorial, we’ll use the latest tag. Tag the image with your Docker Hub username and push it:

docker tag godotagonesmultiplayer:latest docker.io/YOURUSERNAME/godotagonesmultiplayer:latest
docker image push docker.io/YOURUSERNAME/godotagonesmultiplayer:latest

Starting a Game Server

You now have the two main pieces: Agones and a game server image. Next, Agones needs to know how to run that image. You tell it with a Kubernetes manifest, which I named gameserver.yaml. It sets the ports, health checks, CPU and memory for the game server.

apiVersion: agones.dev/v1
kind: GameServer
metadata:
  generateName: multiplayer-game-server-
spec:
  ports:
    - name: default
      portPolicy: Dynamic
      containerPort: 8910
  health:
    # Disable health checking. defaults to false, but can be set to true
    disabled: false
    # Number of seconds after the container has started before health check is initiated. Defaults to 5 seconds
    initialDelaySeconds: 30
    # If the Health() function does not get called at least once every period (seconds), then
    # the game server is not healthy. Defaults to 5
    periodSeconds: 120
    # Minimum consecutive failures for the health probe to be considered failed after having succeeded.
    # Defaults to 3. Minimum value is 1
    failureThreshold: 10
  template:
    spec:
      containers:
        - name: multiplayer-game-server
          image: docker.io/andresromerodev/godotagonesmultiplayer:latest  # Use the latest version of the multiplayer game server image
          imagePullPolicy: Always
          resources:
            requests:
              cpu: "1"       # Reserve 1 CPU core
              memory: "1Gi"  # Reserve 1 GB of memory
            limits:
              cpu: "4"       # Use at most 4 CPU cores
              memory: "8Gi"  # Use at most 8 GB of memory

These are only a few of the settings you can change. For more advanced setups, see the official Agones docs (opens in new tab). This tutorial is about getting your first game server running, so I’ve left out the advanced concepts, but they’re worth learning next.

Now start a game server:

kubectl create -f https://raw.githubusercontent.com/YOURUSERNAME/godot-agones-multiplayer/main/gameserver.yaml

Check that it’s running:

$ kubectl get gameservers
NAME                            STATE   ADDRESS          PORT   NODE                   AGE
multiplayer-game-server-gg79v   Ready   68.183.121.179   7459   pool-3a573me0i-bnc3y   16s

You can also check the server logs. You should see two calls from the server to Agones: one reporting it as ready, and one reporting it as healthy. The health report repeats every 60 seconds to keep the server alive.

$ kubectl logs multiplayer-game-server-gg79v -c multiplayer-game-server
Godot Engine v4.2.2.stable.official.15073afe3 - https://godotengine.org
[AGONES] SDK STARTING UP... PORT FOUND: 9358
[AGONES] POST /ready
Reported game server as ready to Agones...
Waiting For Players!
[AGONES] REQUESTED COMPLETED. RESPONSE_CODE: 200 | CODE: 0
[AGONES] POST /health

Connecting to the Server

Now let’s connect and play. Run two instances of the game in Godot, or export a client build for Windows, Mac or Linux the same way we exported the server. In each client, enter the IP and port shown by kubectl get gameservers.

Lobby with server IP 68.183.121.179 and port 7459 entered

Click “Join” on both clients, and you’ll see new lines in the server logs:

$ kubectl logs multiplayer-game-server-gg79v -c multiplayer-game-server
Player Connected 67851921
Player Connected 231925406

Then pick one client as the leader and click “Start Game.” You’re now playing on a game server running in the cloud.

Two game clients connected to the same match

It’s not much of a game, and the only way to lose is to fall off the platform. But the point was to understand dedicated game servers, not to build great gameplay.

Closing Comments

Kubernetes can be a lot to take in, especially if you’re new to it. If you have questions, reach out to me on LinkedIn or X.

Thanks for reading!

All posts