Minecraft Server on Raspberry Pi

Want to host a Minecraft server for up to 10 players? Want to host the server 24/7 without leaving your PC on? Using a Raspberry Pi to host a small Minecraft server is perfect. The power consumption of a Raspberry Pi is tiny and the performance it can provide will be good for up to 10 friends.

Equipment List:

  • Raspberry Pi 3B/3B+ recommended
  • 8GB MicroSD Card (64GB MicroSD Card recommended – Minecraft server world files can grow rapidly!)
  • Ethernet Cable (preferred to WiFi, but WiFi will work too)

Recommendations:

If you are using a Raspberry Pi 3 or lower, we recommend that you overclock your Pi in order to grab some extra performance that will be massively beneficial to the way your Minecraft server performs. If you wish to do so, please see our Raspberry Pi 3 Overclocking Guide. We strongly recommend applying the overclock for web servers which sets the GPU memory to 16MB.

You’ll want to use a headless Linux distribution such as Raspbian Stretch Lite. It’s important not to install the graphical version as this will use unnecessary resources. Follow our Headless Raspberry Pi Setup Guide. If you plan to use an Ethernet cable directly to your router to provide internet connectivity as recommended, you can skip the WiFi setup part of the headless guide.

Downloading the Minecraft Server

We will start by updating and upgrading the Raspberry Pi by running the following commands:

sudo apt update && sudo apt install upgrade

If you intend to connect to your Raspberry Pi via SSH, you’ll need to install Screen in order for the Java process for the Minecraft server to continue running when you exit your SSH session.

sudo apt install screen

The next stage is to install the server into a dedicated directory. Make a directory called “minecraft” and use the change directory command to open it:

sudo mkdir /home/minecraft
cd /home/minecraft

You’re now ready to download the builder tool from spigotmc.org.

sudo wget https://hub.spigotmc.org/jenkins/job/BuildTools/lastSuccessfulBuild/artifact/target/BuildTools.jar

The Spigot server is written in Java. The latest versions of Raspbian Lite have Java built-in. The following command will take around 20 minutes to complete:

sudo java -jar BuildTools.jar

Building the Minecraft Server

After around 20 minutes, the Minecraft server should have been built. It’s time to launch the server. First, use the ls command to find the correct name of the latest spigot.jar file.

ls

This should display a filename similar to spigot-[version].jar. At the time of writing, this was spigot-1.14.1.jar. Launch the server with the following command, making sure you enter the correct version number.

sudo java -Xms512M -Xmx1008M -jar /home/minecraft/spigot-[version].jar nogui

Wait for the server to stop. Open the EULA.

sudo nano eula.txt

Confirm you accept the EULA by changing False to True, then press Ctrl > X to exit and save.

If you’re using SSH, start a screen session.

screen

Next, relaunch the server:

sudo java -Xms512M -Xmx1008M -jar /home/minecraft/spigot-[version].jar nogui

This time, things will take a bit longer as the map is built. We’re talking 3-5 minutes or so, but this is a one-time only delay. Once the map is created, subsequent restarts will only take half a minute or so.

You can exit the screen by pressing Ctrl > A > D.

To resume the screen session to access the console again type:

screen -ls

There should be one attached screen, for example:

3876.pts-0.minecraftpi	(28/05/19 17:12:53)	(Detached)

In my case, 3876 is the screen session ID. Run the below command:

screen -r 3876 (REPLACE 3876 WITH YOUR SCREEN SESSION ID)

Opening Ports on your Router

You will need to open ports on your router in order for friends outside of your home network to be able to connect to your Minecraft Server. If you will only be playing with people inside your home network, you can skip this step.

This step is largely dependant on your brand of router/internet service provider. We advise you to look up specific instructions online based on your router model/ISP.

Ensure that port 25565 is open both inbound and outbound for your Raspberry Pi’s private IP. If you don’t know your Pi’s IP, you can find it by typing the below on your Pi:

ifconfig

You should get an output similar to this:

pi@minecraftpi:~ $ ifconfig
enxb827eb759b13: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether b8:27:eb:75:9b:13  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.0.80  netmask 255.255.255.0  broadcast 192.168.0.255
        inet6 2a02:c7f:83c:9d00:fae:ca56:7482:3ad4  prefixlen 64  scopeid 0x0<global>
        inet6 fe80::5bc9:f9f:56e9:da6f  prefixlen 64  scopeid 0x20<link>
        inet6 fdf7:9631:2320:0:15ab:5859:12c2:d5b6  prefixlen 64  scopeid 0x0<global>
        ether b8:27:eb:20:ce:46  txqueuelen 1000  (Ethernet)
        RX packets 23995  bytes 5033254 (4.8 MiB)
        RX errors 0  dropped 2997  overruns 0  frame 0
        TX packets 4963  bytes 831365 (811.8 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

Although we’re using WiFi through wlan0 for this demo, it should be clear that our private IP is 192.168.0.80.

Test the Connection to your Server

Now try to connect to your server locally – inside your network. On Minecraft, Direct Connect to the IP “127.0.0.1:25565”. This is your localhost IP.

If that was successful. Find your IP here. Add :25565 to the end of your IP and share it with a friend. Ask them to test the connection from outside of your network. If you have set up your port forwarding correctly and your Minecraft Server is running, there should be no issues.

Configure your Minecraft Server for Higher Performance

Once you know the server is setup correctly and on your network, it’s time to configure it. Begin by editing the server properties. This is a text file that can be accessed with the nano text editor:

sudo nano /home/minecraft/server.properties

Various changes are recommended. Whatever you change here, keep in mind that the Pi is a modest device that cannot handle too much processing.

A list of server properties can be found in the Minecraft wiki, but those you should edit straight away are:

view-distance=5
max-players=5

You may be good to play with up to 10 players, especially if you have a good overclock with cooling applied, but 5 should be the sweet spot for best performance.

Several other options are available to configure that you might be interested in, such as:

pvp = true

This is for player vs. player action. There’s also a difficulty setting:

difficulty = [integer 0-3]

Here, the easiest setting is 0.

Finally, we strongly recommend installing a plugin called NoSpawnChunks, which is designed to prevent too much RAM being used up by the Minecraft server without affecting performance and gameplay. First, open the /plugins subdirectory:

cd /home/minecraft/plugins

Next, download the NoSpawnChunks.jar Java object.

sudo wget -O NoSpawnChunks.jar http://ci.dmulloy2.net/job/NoSpawnChunks/

This will help to keep RAM usage low, ensuring the server doesn’t run slow.

Make your Minecraft Server Launch at Boot

If you’re using the Pi as a dedicated Minecraft server, you’ll probably want to have the server running at all times. While there’s bound to be some minor downtime, a startup script will ensure the server can start itself automatically in the event of a restart, power cut or crash/freeze.

Start by creating a startup script:

sudo nano /home/startminecraft.sh

You can call it whatever you like — choose something meaningful though.

Copy the following into your startminecraft.sh file:

#!/bin/bash
cd /home/minecraft
sudo java -Xms512M -Xmx1008M -jar /home/minecraft/spigot-[version].jar nogui &

You could stop here and just use the startminecraft.sh file to launch the software, after giving it executable permissions:

sudo chmod +x startminecraft.sh

Then, run it with:

./startminecraft.sh

However, if you prefer to have the script run at boot, find the rc.local file, and edit it:

sudo nano /etc/rc.local

At the end, before the exit 0 line, add:

bash /home/minecraft-start.sh

Again, use Ctrl > X to exit and save the file.

Overclocking your Raspberry Pi 3

The Raspberry Pi 3 is a great credit-card sized computer which is far more powerful than it’s predecessors, but you know you can squeeze even more power out of it? Here’s how to overclock your Raspberry Pi and push it that little bit further.

Why Overclock your Raspberry Pi 3?

A standard Raspberry Pi 3 boasts a 1.2GHz 64-bit quad-core CPU, 1GB RAM, along with a Broadcom VideoCore IV GPU.

Overlocking the CPU will result in increasing the default Raspberry Pi clock speed from 1.2GHz up to 1.5GHz, depending upon your cooling solution (such as a heat sink with small fan). Note that as the Raspberry Pi uses a SoC, you’ll need to adjust RAM to accommodate overclocking.

What’s the point of overclocking a Raspberry Pi? Well, it’s simple: you want to get the most possible performance out of it. Several popular tools will work better than intended with overclocking. For example:

Retro gaming: If you’ve been struggling with running Sony PlayStation 1, Sega Dreamcast, or Nintendo N64 games on RetroPie or whatever retro gaming solution you’ve chosen to use, overclocking can help considerably.

Kodi: Performance issues with streaming video in Kodi can be overcome by overclocking your Raspberry Pi.

Exagear: If you’re trying to run Windows OS on your Raspberry Pi, you can get a nice performance boost by overclocking.

Desktop: Raspberry Pi 3 can be used as a standard desktop. Why wouldn’t you want a bit of additional performance with a simple overclock?

Overclocking a Raspberry Pi 3 is a practical response to some of its shortcomings. Although, most of these were dealt with in the latest Raspberry Pi 3B+ model.

Is Overclocking your Raspberry Pi 3B Safe?

While overclocking Raspberry Pi is fast and easy, it is not always without risk.

Heat is generated: Cooling solutions are always required if you plan to overclock your Pi. Heat is bad for computer systems, as it slows processing, which in turn generates heat. We strongly recommend a solid cooling setup.

Component failure: Increased heat can also result in the failure of components.

Data corruption: Using increased clock speeds more often results in corrupted data compared to a lower clock rate. If you’re using a hard disk drive for your Pi’s operating system, this shouldn’t be a massive issue. However, if your Raspberry Pi relies on a microSD card (most do), then you may find flash media is less reliable.

Reliable power supply: You should already be using a good quality power supply for your Raspberry Pi. Anything less than the recommended 2.5amp power adaptor is unsuitable for overclocking. Data corruption will quickly occur with a low quality power supply.

Changing certain settings during an overclocking attempt on your Raspberry Pi would void the warranty. We will highlight which settings these are in case you do not want to risk voiding the warranty of your device.

How to Overclock your Raspberry Pi 3

Still want to overclock your Raspberry Pi? Although you can overclock on other distros, we’ll be looking at the process on Raspbian Stretch as it’s by far the most popular request. Begin by running a full update and upgrade:

sudo apt update && sudo apt install upgrade

With that done, install the sysbench tool:

sudo apt install sysbench

You’ll need this later for checking how overclocking has improved performance. For now, however, run sysbench to get a baseline:

sysbench --test=cpu --cpu-max-prime=2000 --num-threads=4 run

Make a note of the results, or append a destination file to output the results to for comparison later.

sysbench --test=cpu --cpu-max-prime=2000 --num-threads=4 run > benchmark-before.txt

Next, you’ll need to edit the config.txt file. You’ll find this in the boot directory, which is best accessed via the terminal.

Begin by switching to the boot directory

cd /boot

Confirm you’re in the right location by listing the contents.

ls

You should spot config.txt. At this point it is worth nothing that the boot directory is the only portion of your Raspberry Pi’s operating system that is accessible from Windows. We’ll come back to that later. For now, just make a copy of the file:

sudo cp config.txt config.old

You should now have two config files. The first is the one you can edit, config.txt; the second is your backup, config.old.

To edit config.txt:

sudo nano config.txt

Here, you’ll find a list of settings, in the format “name=value”. Look for “overclock”; you should find a line that reads “#Uncomment to overclock the arm.” Remove the hashtag from the first line beneath, #arm_freq=800.

To overclock your Raspberry Pi 3 significantly, you’ll need to enter values for the following four conditions:

  1. arm_freq
  2. core_freq
  3. sdram_freq
  4. over_voltage

For the Raspberry Pi 3, it’s most common to overclock with the following:

arm_freq=1350
core_freq=500
sdram_freq=500
over_voltage=6
disable_splash=1

These settings are the maximum stable clock speed you’re likely to get. Lower options are available, but somewhat pointless. However, as noted elsewhere, the software you’re running will determine whether or not you’re happy with the overclocked speed. Overclocking at the above stable recommendations will not void your warranty.

If you are using the Raspberry Pi 3 as a gaming emulator, media player or using a desktop environment (LXDE, XFCE, Maynard, etc) then you’ll want to increase gpu_mem to at least 256. On the other hand, if you are using the Raspberry Pi as a web server, to build a drone or simply a console-based project then you should lower gpu_mem to 16. In other words, if your needs are graphical increase GPU’s memory, if not, lower it to the minimum.

If you’re happy to void the warranty on your Pi and have a good cooling solution, you could apply the below configurations for absolute maximum performance:

Webserver:

arm_freq=1350
core_freq=500
sdram_freq=500
over_voltage=6
gpu_mem=16
disable_splash=1
force_turbo=1 #VOIDS WARRANTY - Keeps clock rate at maximum constantly.
boot_delay=1 #helps to avoid sdcard corruption when force_turbo is enabled.

Graphical:

arm_freq=1350
core_freq=500
sdram_freq=500
over_voltage=6
gpu_mem=320
disable_splash=1
force_turbo=1 #VOIDS WARRANTY - Keeps clock rate at maximum constantly.
boot_delay=1 #helps to avoid sdcard corruption when force_turbo is enabled.

Check Overclock Performance Gain with Sysbench

Now the system is overclocked, you should run the sysbench tool again:

sysbench --test=cpu --cpu-max-prime=2000 --num-threads=4 run > benchmark-after.txt

Compare the difference between benchmark-after.txt and benchmark-before.txt. This should highlight the performance improvements you got from overclocking. The lower the total time, the better the performance of the CPU. Feel free to adjust the overclock settings. Do this small steps at a time. We recommend no more than 50Mhz adjustments at a time.

How to Recover a Failed Overclock

If you’ve rebooted your Raspberry Pi with overclocked settings and found that it won’t boot, or it crashes, freezes, of behaves in some other undesirable manner, you’ll need to undo your changes. This is easily done by restoring the backup we created earlier:

  • Power off the Raspberry Pi.
  • Remove the microSD card.
  • Insert the card into your PC’s card reader.
  • Delete \boot\config.txt.
  • Rename \boot\config.old to config.txt.
  • Safely remove the microSD card, replace in your Pi, and boot.

Everything should now be back to normal. You may continue to overclock.

Setting up a 5v Relay

Often you may wish to control modules with a higher voltage with the Raspberry Pi. For this purpose, relays can be used on the Raspberry Pi. The relay is essentially a switch that is switched by means of a low-voltage pulse. Relay modules generally come in sizes ranging from 1 channel to 16 channels. Relays are widely used on Raspberry Pi projects that involve home automation. For example, switching on and off a light using voice commands.

Equipment List

  • Any Raspberry Pi with GPIO pins – 3B/3B+ recommended
  • Jumper Wires
  • 12v DC Switching Power Supply
  • A 12v device to test with, i.e PC fan, motor, LED strip etc
  • Relay

Setting up the Hardware

In the setup in the diagram below, we demonstrate using a 12v PC fan.

Complete the below jumper cabling plan between the Pi, power supply, relay and fan/device you choose to use. Some people may find it easier to follow the image above, rather than the cable map below. They’re identical.

Cable Map:

Pin 2 (5v) on Pi <=> VCC on relay
Pin 6 (ground) on Pi <=> GND on relay
Pin 40 (BCM21) on PI <=> IN1 on relay
Negative wire from fan <=> Negative terminal on 12v DC power supply
Positive wire from fan <=> Normally Open (NO) terminal of relay
Positive wire from 12v DC power supply <=> Common (C) terminal of relay (the middle one)

Setting up the Software

By following the above hardware setup exactly, you have chosen BCM21 as the GPIO pin for switching the relay on/off.

We need to ensure the Pi is up to date and has some essential software installed.

sudo apt-get update
sudo apt-get install nano

Create a file called script.py in /home.pi

cd /home/pi
nano script.py

Paste the below code inside and save the file.

import RPi.GPIO as GPIO
import time

#GPIO pin number
channel = 21

# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.OUT)

# Turn fan on
def motor_on(pin):
    GPIO.output(pin, GPIO.HIGH) 

# Turn fan off
def motor_off(pin):
    GPIO.output(pin, GPIO.LOW) 


if __name__ == '__main__':
    try:
        motor_on(channel)
        time.sleep(2)
        motor_off(channel)
        time.sleep(2)
        GPIO.cleanup()
    except KeyboardInterrupt:
        GPIO.cleanup()

Run the script

python script.py

Headless Raspberry Pi Setup

Setting up a Raspberry Pi is easy. Setting up a headless Raspberry Pi should take no longer than 30 minutes. There is no requirement for a screen, keyboard or mouse, hence the use of the word headless. This option is perfect for setting up your Pi for something like a web server, Minecraft server, file server etc.

Equipment/Software List

Equipment:

  • Raspberry Pi 3B/3B+ recommended
  • Micro USB Power Supply
  • 8GB+ MicroSD Card/8GB+ USB Flash Drive (if you are using 3B+)
  • A computer with MicroSD slot/adapter (if you are using a MicroSD card)

SD Card Setup

You will also need to download the latest version of Raspbian. We strongly recommend the Stretch Lite version if you do not need a GUI. Raspbian Stretch Lite is lightweight and downloads pretty fast on a modern connection.

Once the image is downloaded and decompressed, you will have to install it on the SD card. Download and install Etcher Balena. It’s a free software that allows you to unpack and install the ISO on your SD Card. It’s available on Windows, Mac and Linux.

Once Etcher is installed, plug in your SD card or USB flash drive. Open Etcher. Click “Select Image” and choose the Raspbian ISO you downloaded. Next, click “Select Drive” and choose the SD card you just plugged in. Finally, press “Flash!”. This should take 5-10 minutes to complete. Take a short break, you deserve it.

Enabling Wifi & SSH

Once Etcher tells you the process is complete, close Etcher but keep the SD card plugged in. Navigate to the SD card and open it via This PC (for Windows) or Finder (for Mac). It’s usually labelled “BOOT”.

Create a blank file in the root directory of the SD card called “ssh”. This file must be empty and only have the letters “ssh” in the file name – no file extension. This will tell the Pi to enable SSH when you first boot the Pi.

Finally, we need to create a file called wpa_supplicant.conf in the root directory of the SD card, just like we did for the ssh file. Copy the below configuration and paste it into the wpa_supplicant.conf file. You must update the country code on the first line to your country. Use your countries ISO 3116 alpha-2 code. You can find a list of the codes here.

country=GB
update_config=1
ctrl_interface=/var/run/wpa_supplicant

network={
 scan_ssid=1
 ssid="MyNetworkSSID"
 psk="Pa55w0rd12345"
}

Once this is done, save the file. You may now eject the SD card safely and plug it into the Raspberry Pi. Power on the Pi. You should see a solid red LED and a flashing green activity LED on the Pi. Allow 2 minutes for the Pi to fully boot for the first time. Find the IP your Pi has taken from your router via DHCP. To do this, you can navigate to your router’s admin control panel and check the list of connected devices. Look for the IP next to the Raspberry Pi. Use this IP to connect via SSH. If you’re Windows, we recommend using PuTTY as your SSH terminal. On Mac/Linux, terminal is fine (ssh pi@IPADDRESS). The default username and password is “pi” and “raspberry”.

Measure Temperature and Humidity with DHT11/DHT22 Sensor

With very little knowledge and effort, it is easy to measure the temperature and humidity using a sensor. Sensors such as the DHT11 and DHT22 are affordable, accurate and can measure both temperature and humidity.

Equipment List

To make this tutorial easier, we will be using a DHT11/DHT22 with PCB. Therefore there is no need to use a 10kΩ resistor.

  • Raspberry Pi 3B/3B+ recommended
  • DHT11 or DHT22 humidity sensor
  • Jumper Wires

You can see the difference between the DHT11 and DHT22 here. In short, the DHT11 is cheaper, but the DHT22 is more precise and lasts longer. For applications in areas where accuracy and reliability is more important, the DHT22 should be used. Personally, we think the DHT22 should be used wherever possible as its only slightly more expensive.

Setting up the Hardware


The left pin of the sensor is connected to 3V3 of Pi (pin1), the second pin on the sensor is connected to a free GPIO pin on the raspberry (GPIO26, pin37) and the right pin of the sensor goes to GND (Pin9) on the Pi. The setup is identical for both DHT11 and DHT22 since the pins are assigned the same way.

Getting Readings from the Sensor on the Raspberry Pi

Before continuing, the below steps assume your Pi has Raspbian installed and is connected to the internet. If you haven’t done this yet, please follow the steps here.

We need to install some packages:

sudo apt-get update 
sudo apt-get install build-essential python-dev python-openssl git

Now we need the library for the sensors. We use a pre-built Adafruit library that supports the DHT11 and DHT22:

cd /home/pi
git clone https://github.com/adafruit/Adafruit_Python_DHT.git && cd Adafruit_Python_DHT 
sudo python setup.py install

This creates the Adafruit Python library that we can easily integrate into our projects. If everything went well, we should be able to read the temperature and humidity. Let’s test our setup with the example script provided by Adafruit. The first parameter (22) indicates which sensor we are using (11 if you are using the DHT11) and the second is which GPIO it is connected to (not the pin number, but the GPIO number). Run these commands:

cd examples
sudo ./AdafruitDHT.py 22 26

This produces an output like the following:

pi@how2pi:~ $ sudo ./AdafruitDHT.py 22 26
Temp=23.2*  Humidity=45.1%

Be aware: Both DHT11 and DHT22 can only read at a rate of every 2 seconds. We recommend a minimum interval of 3-5 seconds.

In order to utilise the temperature and humidity library into other Python scripts, you only need the following code:

import Adafruit_DHT
...
sensor = Adafruit_DHT.DHT11
pin = 4
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
...