Learning objectives
After reading this article you will be able to:
- Download Lavalink and set the port, password and sources in application.yml
- Size the JVM memory and connect a discord.js bot with Shoukaku
- Check that the server answers and fix the most common errors
On this page
Running Lavalink on your own computer takes one command. Keeping it up for a music bot that plays all day takes more: the right Java version, a password that isn't the sample one, a memory cap for the JVM and an address the bot can reach.
This guide covers the whole path, from the download to the first song playing. If you don't know yet what Lavalink does and why it runs apart from the bot, start with what is Lavalink.
What do you need before you start?#
- Java on a recent LTS release. The Lavalink docs list the minimum version. Check yours with
java -version. - A Lavalink release with DAVE support. Discord requires end-to-end encryption (the DAVE protocol) on voice calls, server voice channels included, according to its voice connections docs. Use a Lavalink release that supports DAVE and check the release notes to see whether your bot's client library needs an update too.
- An always-on machine with free memory for the JVM on top of what the system already uses.
- A Discord bot that already connects and answers commands. If you don't have one, see how to make your first Discord bot.
How do you download and configure Lavalink?#
- Create a folder just for the server and download
Lavalink.jarinto it from the project's releases page on GitHub. Skip mirrors and third-party jars: the file runs with the permissions of whoever starts it. - In the same folder, create
application.yml:
server:
port: ${PORT:2333}
address: 0.0.0.0
lavalink:
server:
# the password comes from the LAVALINK_SERVER_PASSWORD environment variable
sources:
youtube: false
soundcloud: true
bandcamp: true
twitch: true
vimeo: true
http: false
local: false- Set the password and start the server:
export LAVALINK_SERVER_PASSWORD="a-long-random-password"
java -jar Lavalink.jarTwo things make this file portable. Lavalink is a Spring Boot application, and Spring resolves ${PORT:2333} from the PORT environment variable, falling back to 2333 when it isn't set (Spring Boot docs). Lavalink also reads any key of the file from an environment variable, which takes precedence over the file: lavalink.server.password becomes LAVALINK_SERVER_PASSWORD (docs). That keeps the password out of your repository. With no password at all, the server refuses every connection, which beats accepting all of them.
About the sources: the project's sample application.yml warns that leaving http on without a proxy can expose the server's IP address, so it is off here. The built-in YouTube source is deprecated and stays false. Playing YouTube needs the project's own youtube-source plugin and runs into blocks and terms of service, all covered in why your music bot stopped playing YouTube.
How much memory should the JVM get?#
Without -Xmx, the JVM picks the heap ceiling on its own: by default, 25% of the memory it can see (-XX:MaxRAMPercentage, in the java command docs). On a 4 GB machine that is about 1 GB, which may be too much or too little. Set the ceiling yourself (the 512 MB below is only a starting point for testing):
java -Xmx512m -jar Lavalink.jarThe heap isn't all the memory the process uses. The JVM also takes memory outside it, such as metaspace and native buffers, and Oracle's troubleshooting guide treats each of those areas as a separate error. That is why -Xmx has to stay below the available RAM, with headroom.
The official examples use -Xmx4G for systemd and -Xmx6G for Docker (in JAVA_TOOL_OPTIONS). They are examples, not a minimum: real usage depends on how many players run at once, the filters and the plugins. Measure with a few songs playing in different servers and watch the peak. How much RAM a Discord bot needs helps you size the bot side.
How do you connect a discord.js bot?#
Lavalink clients are community-maintained and listed at lavalink.dev/clients. This example uses Shoukaku, which speaks version 4 of the Lavalink API and ships a discord.js connector. Install the latest release:
npm install discord.js shoukakuIn the bot's .env:
DISCORD_TOKEN=paste_the_token_here
LAVALINK_URL=localhost:2333
LAVALINK_PASSWORD=the-same-password-as-the-server
LAVALINK_SECURE=falseShoukaku's url is just host and port, with no http://. secure switches to HTTPS and WSS: keep it false against localhost:2333 and set it to true when a TLS proxy sits in front, on port 443.
index.js (with "type": "module" in package.json):
import { Client, Events, GatewayIntentBits } from "discord.js";
import { Connectors, LoadType, Shoukaku } from "shoukaku";
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates],
});
const nodes = [
{
name: "main",
url: process.env.LAVALINK_URL, // host:port, no http://
auth: process.env.LAVALINK_PASSWORD,
secure: process.env.LAVALINK_SECURE === "true",
},
];
const shoukaku = new Shoukaku(new Connectors.DiscordJS(client), nodes);
shoukaku.on("ready", (name) => console.log(`Lavalink connected: ${name}`));
shoukaku.on("error", (name, error) => console.error(`Lavalink ${name}:`, error));
function firstTrack(result) {
if (result?.loadType === LoadType.TRACK) return result.data;
if (result?.loadType === LoadType.SEARCH) return result.data[0];
if (result?.loadType === LoadType.PLAYLIST) return result.data.tracks[0];
return undefined;
}
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand() || interaction.commandName !== "play") return;
if (!interaction.inCachedGuild()) return;
const channel = interaction.member.voice.channel;
if (!channel) {
await interaction.reply("Join a voice channel first.");
return;
}
await interaction.deferReply();
const node = shoukaku.getIdealNode();
if (!node) {
await interaction.editReply("No Lavalink server is connected.");
return;
}
const query = interaction.options.getString("query", true);
const result = await node.rest.resolve(
query.startsWith("https://") ? query : `scsearch:${query}`,
);
const track = firstTrack(result);
if (!track) {
await interaction.editReply("Nothing found.");
return;
}
const player =
shoukaku.players.get(interaction.guildId) ??
(await shoukaku.joinVoiceChannel({
guildId: interaction.guildId,
channelId: channel.id,
shardId: interaction.guild.shardId,
}));
await player.playTrack({ track: { encoded: track.encoded } });
await interaction.editReply(`Now playing: ${track.info.title}`);
});
client.login(process.env.DISCORD_TOKEN);The GuildVoiceStates intent is required: without it, the bot doesn't receive the voice updates the client forwards to Lavalink, and it can't tell which channel the user is in. The scsearch: prefix searches SoundCloud, as the Lavalink REST API documents.
/play needs a text option (registering commands is covered in how to create slash commands). In the deploy-commands.js from how to make your first Discord bot, replace the command definition with:
new SlashCommandBuilder()
.setName("play")
.setDescription("Plays a song")
.addStringOption((option) =>
option.setName("query").setDescription("Name or link").setRequired(true),
),Run the bot with node --env-file=.env index.js.
How do you check that Lavalink works?#
Check in four steps, from the server to the bot:
- In the server log, wait for this line:
Lavalink is ready to accept connections.- Test the password. Every route requires the
Authorizationheader,/versionincluded, which returns the version as plain text:
curl -H "Authorization: $LAVALINK_SERVER_PASSWORD" http://localhost:2333/version- Check the sources.
GET /v4/infolists the enabled ones undersourceManagers:
curl -H "Authorization: $LAVALINK_SERVER_PASSWORD" http://localhost:2333/v4/info- In the bot log, look for
Lavalink connected: main. Join a voice channel and use/play.
What are the most common errors?#
401or403. Lavalink answers 401 when theAuthorizationheader is missing and 403 when the password doesn't match; the log saysAuthorization missingorAuthorization failed. Compare the bot's and the server's variables, with no stray spaces or quotes.- Connection refused or timed out. The server listens on another port, only on
127.0.0.1, or a firewall blocks the path. Keepaddress: 0.0.0.0and check the port in the startup log. - Wrong
securevalue.trueagainst a port without TLS, orfalseagainst an HTTPS proxy on 443, drops the connection before authentication. UnsupportedClassVersionErrorat startup. The JVM is older than Lavalink requires and can't read classes compiled for a newer release. Update Java.java.lang.OutOfMemoryError: Java heap space. The heap is full. Raise-Xmxwithin the available RAM. If the whole process runs out, the system kills it; see out-of-memory errors.Can't find any nodes to connect on. Shoukaku tried to join a channel with no node connected: the bot hasn't finished connecting to Lavalink yet, or the connection failed for one of the reasons above. Read theerrorandcloseevents.- The bot joins the channel and stays silent. Check that both server and client are on releases with DAVE support, that the
GuildVoiceStatesintent is on and that the search returned tracks. If only YouTube fails, that is a different problem, covered in the YouTube article above.
How do you keep Lavalink up all the time?#
If it goes down, every song stops while the bot stays online, unable to play. On a Linux VPS, the official docs point to systemd, which restarts the process when it fails:
[Unit]
Description=Lavalink
After=network.target
[Service]
User=lavalink
WorkingDirectory=/opt/lavalink
EnvironmentFile=/opt/lavalink/lavalink.env
ExecStart=/usr/bin/java -Xmx512m -jar /opt/lavalink/Lavalink.jar
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=multi-user.targetlavalink.env holds LAVALINK_SERVER_PASSWORD=... and should be readable only by the service user. If the bot runs on another machine, put a reverse proxy with TLS in front (the bot connects on 443 with secure: true) or allow port 2333 only from the bot's IP. The rest (monitoring, updates, restarts) follows the same reasoning as keeping a Discord bot online 24/7.
How to do this on Square Cloud#
On Square Cloud, Lavalink runs as a separate web application on the Java runtime, from 512 MB, next to the bot in the same account. You upload Lavalink.jar and application.yml in a ZIP through the dashboard, the CLI, GitHub or the VS Code extension. The platform starts the .jar with java -jar, and JVM flags go in the start command (START). One example is java -Xmx512m -jar Lavalink.jar: tune -Xmx to the application's memory and to the usage you measure, leaving headroom for memory outside the heap. The squarecloud.app file is optional: the dashboard generates it on deploy, or you write it at the project root.
The platform sets the PORT variable and expects the web application on 0.0.0.0 at that port. The example's ${PORT:2333} reads that variable; check the startup log for the port Lavalink came up on. Put LAVALINK_SERVER_PASSWORD in the application's environment variables; the change applies on the next restart. The bot connects to Lavalink's *.squareweb.app subdomain on port 443 with secure: true: LAVALINK_URL=your-lavalink.squareweb.app:443 and LAVALINK_SECURE=true.
The bot lives in a background application, with at least 256 MB from the plan's RAM pool. If Lavalink goes over the application's memory, the application stops and doesn't come back on its own: raise its RAM and start it again. In the real-time logs, wait for the Lavalink is ready to accept connections. line. See the details of Java and Lavalink hosting.
Bot hosting
Keep your bot online 24/7 with automatic restarts
FAQs
Which Java version does Lavalink need?
The minimum is listed in the official Lavalink docs; use a recent Java LTS. A JVM that is too old fails right at startup with UnsupportedClassVersionError.
How much memory does Lavalink use?
It depends on how many players run at once, the filters and the plugins. Cap the heap with -Xmx below the available RAM, because the JVM also uses memory outside the heap, and adjust it from measured usage.
Do I need to expose port 2333 to the internet?
Not if there is an HTTPS proxy in front: the bot connects on port 443 over a secure connection and 2333 stays internal. Without a proxy, allow the port only from the bot's address and use a long password.
Can one Lavalink server handle several bots?
Yes. Each bot connects with the server password and opens its own session. When the load grows, run more than one node and let the client pick between them.
More in Bots
See all 39 articles- How much does it cost to host a Discord bot?The cost of hosting a Discord bot depends on RAM, uptime, database and outside services. Learn how to estimate your own bill and where the money goes.
- Running a bot on your phone or PC vs hosting itA bot on your PC or phone (Termux) goes offline when the device shuts down, sleeps or loses its network. Compare the three options and when each one fits.
- How to host a Discord bot 24/7To keep a Discord bot online 24/7, run its process on an always-on machine with automatic restarts. Compare your PC, a VPS with pm2 or systemd, and bot hosting.
- Why your Discord bot keeps going offline (and how to fix it)A Discord bot goes offline when the process dies, the token is invalid, an intent is disabled or memory runs out. Learn to diagnose each cause and fix it.