Most High Efficiency (HE) machines require HE detergent.   Using non-HE detergent will cause too many suds to form. These suds will leave behind a residue that can start to smell. Don't use too much detergent either. This will also cause residue to form inside your washing machine. Powdered detergent often is a better alternative to liquid as it tends to produce fewer suds. Use dryer sheets instead.  Much like liquid detergent, liquid fabric softener can also cause residue to build up inside your machine. This residue will develop a bad odor over time. Buy dryer sheets instead. These are inexpensive and can be found in the laundry aisle of any supermarket. This will decrease the mold build-up as it allows the tub to dry completely.  Leave the door slightly ajar when the machine is not in use. This will allow fresh air to circulate through the drum of the front loading washing machine and will help dry any remaining moisture after a load. If you have small children or pets, you should avoid doing this as they can climb into the drum and become accidentally trapped inside. Right after a cycle ends, take the wet clothes out.  Set your washer to beep when a cycle is complete, so you don't forget to take the clothes out. If you can't dry your clothes right away, take them out and put them in a hamper or lay them flat until the dryer is available. This will prevent excess moisture from building up inside the washing machine drum after each load. Do this is a dry towel.   Ideally, the gasket, the area underneath it and the inside of the drum should be wiped dry after each cycle. This can be time consuming and a nuisance, so be sure to do this periodically at the very least. You can also wipe down the gaskets with hot soapy water regularly and allow them to completely dry. This will keep them clean and free of mildew. Use a hot water or cleaning cycle.   Pour two cups of white vinegar into the detergent dispenser and run a hot water or cleaning cycle. You can also use a commercial washing machine cleaner such as Smelly Washer, but vinegar is more cost effective and just as efficient. When finished, clean the inside of the tub, gasket, detergent dispenser and inside of the door with a mixture of hot water and vinegar and a towel. Repeat wiping down the inside parts of the washer with hot water only. Run your washer again with hot water only. Leave your washer door open to let the inside of the unit dry.

Summary:
Use the right detergent. Avoid liquid fabric softener. Air out the washing machine between loads. Remove wet clothes immediately. Wipe down the gasket regularly. Clean your washing machine once a month.