Even though gnats are harmless, they can really be a nuisance. As you stated, they are attracted by rotten food and fruits.
Here is one method you might try to get rid of a larger number. Take a jar and fill it almost to the top with vinegar (they are attracted to the smell of vinegar). Poke some small holes in the top of the jar. The gnats will be able to get it but will not be able to get out and will drown in the vinegar. Best to put this behind something or out of sight as it can fill up relatively quickly if you have a larger number.
However, to prevent them, you need to get rid of the sources and that is done through sanitation and cleaning methods.
If you need followup, just hit reply. Please be sure to hit ACCEPT so I receive credit for my help today.
Plastic tubs will work as well. You can also mix a little dawn detergent in with the vinegar as well.
Unfortunately, as long as you have these messes, you are likely to continue to have the gnats crop up from time to time.
Jars are probably better. Those are what I have seen used but I would think that the plastic would also work and are usually more readily available. Although a pickle jar or such would work.